Ejemplo n.º 1
0
 public override CompileResult Execute(IEnumerable<FunctionArgument> arguments, ParsingContext context)
 {
     var functionArguments = arguments as FunctionArgument[] ?? arguments.ToArray();
     ValidateArguments(functionArguments, 2);
     var startDate = System.DateTime.FromOADate(ArgToInt(functionArguments, 0));
     var endDate = System.DateTime.FromOADate(ArgToInt(functionArguments, 1));
     WorkdayCalculator calculator = new WorkdayCalculator();
     var weekdayFactory = new HolidayWeekdaysFactory();
     if (functionArguments.Length > 2)
     {
         var holidayArg = functionArguments[2].Value;
         if (Regex.IsMatch(holidayArg.ToString(), "^[01]{7}"))
         {
             calculator = new WorkdayCalculator(weekdayFactory.Create(holidayArg.ToString()));
         }
         else if (IsNumeric(holidayArg))
         {
             var holidayCode = Convert.ToInt32(holidayArg);
             calculator = new WorkdayCalculator(weekdayFactory.Create(holidayCode));
         }
         else
         {
             return new CompileResult(eErrorType.Value);
         }
     }
     var result = calculator.CalculateNumberOfWorkdays(startDate, endDate);
     if (functionArguments.Length > 3)
     {
         result = calculator.ReduceWorkdaysWithHolidays(result, functionArguments[3]);
     }
     return new CompileResult(result.NumberOfWorkdays, DataType.Integer);
 }
Ejemplo n.º 2
0
        private static object HandleArgumentNotResolved(ParsingContext context, ParameterInfo parameterInfo)
        {
            var attribute = parameterInfo.GetCustomAttribute<ArgumentAttribute>();
            if(attribute == null)
            {
                throw new ArgumentException(string.Format("Could not resolve argument: {0}", parameterInfo.Name));
            }

            var startPosition = context.CurrentPosition;
            var separatorPosition = attribute.Separator == '\0' ? -1 : context.Packet.Data.DataAsString.IndexOf(attribute.Separator, startPosition);
            var length = (separatorPosition == -1 ? context.Packet.Data.DataAsString.Length : separatorPosition) - startPosition;
            var valueToParse = context.Packet.Data.DataAsString.Substring(startPosition, length);

            context.CurrentPosition += length + 1;

            switch(attribute.Encoding)
            {
                case ArgumentAttribute.ArgumentEncoding.HexNumber:
                    return Parse(parameterInfo.ParameterType, valueToParse, NumberStyles.HexNumber);
                case ArgumentAttribute.ArgumentEncoding.DecimalNumber:
                    return Parse(parameterInfo.ParameterType, valueToParse);
                case ArgumentAttribute.ArgumentEncoding.BinaryBytes:
                    return context.Packet.Data.DataAsBinary.Skip(startPosition).ToArray();
                case ArgumentAttribute.ArgumentEncoding.HexBytesString:
                    return valueToParse.Split(2).Select(x => byte.Parse(x, NumberStyles.HexNumber)).ToArray();
                default:
                    throw new ArgumentException(string.Format("Unsupported argument type: {0}", parameterInfo.ParameterType.Name));
            }
        }
Ejemplo n.º 3
0
 private void Calculate(IEnumerable<FunctionArgument> items, ref double nItems, ParsingContext context, ItemContext itemContext)
 {
     foreach (var item in items)
     {
         var cs = item.Value as ExcelDataProvider.IRangeInfo;
         if (cs != null)
         {
             foreach (var c in cs)
             {
                 _CheckForAndHandleExcelError(c, context);
                 if (ShouldIgnore(c, context) == false && ShouldCount(c.Value, ItemContext.InRange))
                 {
                     nItems++;
                 }
             }
         }
         else
         {
             var value = item.Value as IEnumerable<FunctionArgument>;
             if (value != null)
             {
                 Calculate(value, ref nItems, context, ItemContext.InArray);
             }
             else
             {
                 _CheckForAndHandleExcelError(item, context);
                 if (ShouldIgnore(item) == false && ShouldCount(item.Value, itemContext))
                 {
                     nItems++;
                 }
             }
         }
     }
 }
Ejemplo n.º 4
0
 public override CompileResult Execute(IEnumerable<FunctionArgument> arguments, ParsingContext context)
 {
     ValidateArguments(arguments, 2);
     var row = ArgToInt(arguments, 0);
     var col = ArgToInt(arguments, 1);
     ThrowExcelErrorValueExceptionIf(() => row < 0 && col < 0, eErrorType.Value);
     var referenceType = ExcelReferenceType.AbsoluteRowAndColumn;
     var worksheetSpec = string.Empty;
     if (arguments.Count() > 2)
     {
         var arg3 = ArgToInt(arguments, 2);
         ThrowExcelErrorValueExceptionIf(() => arg3 < 1 || arg3 > 4, eErrorType.Value);
         referenceType = (ExcelReferenceType)ArgToInt(arguments, 2);
     }
     if (arguments.Count() > 3)
     {
         var fourthArg = arguments.ElementAt(3).Value;
         if(fourthArg.GetType().Equals(typeof(bool)) && !(bool)fourthArg)
         {
             throw new InvalidOperationException("Excelformulaparser does not support the R1C1 format!");
         }
         if (fourthArg.GetType().Equals(typeof(string)))
         {
             worksheetSpec = fourthArg.ToString() + "!";
         }
     }
     var translator = new IndexToAddressTranslator(context.ExcelDataProvider, referenceType);
     return CreateResult(worksheetSpec + translator.ToAddress(col, row), DataType.ExcelAddress);
 }
Ejemplo n.º 5
0
Archivo: Mod.cs Proyecto: acinep/epplus
 public override CompileResult Execute(IEnumerable<FunctionArgument> arguments, ParsingContext context)
 {
     ValidateArguments(arguments, 2);
     var n1 = ArgToDecimal(arguments, 0);
     var n2 = ArgToDecimal(arguments, 1);
     return new CompileResult(n1 % n2, DataType.Decimal);
 }
Ejemplo n.º 6
0
 public override CompileResult Execute(IEnumerable<FunctionArgument> arguments, ParsingContext context)
 {
     ValidateArguments(arguments, 3);
     var values = GetMatchingValues(arguments, context);
     if (!values.Any()) return CreateResult(0d, DataType.Integer);
     return CreateResult(values.Max(), DataType.Integer);
 }
Ejemplo n.º 7
0
 public override CompileResult Execute(IEnumerable<FunctionArgument> arguments, ParsingContext context)
 {
     ValidateArguments(arguments, 1);
     var nItems = 0d;
     Calculate(arguments, ref nItems, context, ItemContext.SingleArg);
     return CreateResult(nItems, DataType.Integer);
 }
Ejemplo n.º 8
0
 public override CompileResult Compile(IEnumerable<Expression> children, ParsingContext context)
 {
     var args = new List<FunctionArgument>();
     Function.BeforeInvoke(context);
     var firstChild = true;
     foreach (var child in children)
     {
         if (!firstChild || Function.SkipArgumentEvaluation)
         {
             child.ParentIsLookupFunction = Function.IsLookupFuction;
         }
         else
         {
             firstChild = false;
         }
         var arg = child.Compile();
         if (arg != null)
         {
             BuildFunctionArguments(arg.Result, arg.DataType, args);
         }
         else
         {
             BuildFunctionArguments(null, DataType.Unknown, args);
         }
     }
     return Function.Execute(args, context);
 }
Ejemplo n.º 9
0
 public override CompileResult Execute(IEnumerable<FunctionArgument> arguments, ParsingContext context)
 {
     ValidateArguments(arguments, 1);
     var val = arguments.ElementAt(0).ValueFirst;
     if (val is string) return CreateResult(val, DataType.String);
     return CreateResult(string.Empty, DataType.String);
 }
Ejemplo n.º 10
0
 public override CompileResult Execute(IEnumerable<FunctionArgument> arguments, ParsingContext context)
 {
     ValidateArguments(arguments, 1);
     var arg = ArgToDecimal(arguments, 0);
     var result = System.Math.Sqrt((double)arg);
     return CreateResult((double)result, DataType.Decimal);
 }
Ejemplo n.º 11
0
 public override CompileResult Execute(IEnumerable<FunctionArgument> arguments, ParsingContext context)
 {
     ValidateArguments(arguments, 2);
     var firstArg = arguments.ElementAt(0);
     var args = firstArg.Value as IEnumerable<FunctionArgument>;
     if (args == null && firstArg.IsExcelRange)
     {
         args = new List<FunctionArgument>(){ firstArg };
     }
     var criteria = arguments.ElementAt(1).Value;
     ThrowExcelErrorValueExceptionIf(() => criteria == null || criteria.ToString().Length > 255, eErrorType.Value);
     var retVal = 0d;
     if (arguments.Count() > 2)
     {
         var secondArg = arguments.ElementAt(2);
         var lookupRange = secondArg.Value as IEnumerable<FunctionArgument>;
         if (lookupRange == null && secondArg.IsExcelRange)
         {
             lookupRange = new List<FunctionArgument>() {secondArg};
         }
         retVal = CalculateWithLookupRange(args, criteria.ToString(), lookupRange, context);
     }
     else
     {
         retVal = CalculateSingleRange(args, criteria.ToString(), context);
     }
     return CreateResult(retVal, DataType.Decimal);
 }
Ejemplo n.º 12
0
 public override CompileResult Execute(IEnumerable<FunctionArgument> arguments, ParsingContext context)
 {
     ValidateArguments(arguments, 1);
     var dateInt = ArgToInt(arguments, 0);
     var date = System.DateTime.FromOADate(dateInt);
     return CreateResult(WeekNumber(date), DataType.Integer);
 }
Ejemplo n.º 13
0
Archivo: N.cs Proyecto: Eagle-Chan/KIS
 public override CompileResult Execute(IEnumerable<FunctionArgument> arguments, ParsingContext context)
 {
     ValidateArguments(arguments, 1);
     var arg = GetFirstValue(arguments);
     
     if (arg is bool)
     {
         var val = (bool) arg ? 1d : 0d;
         return CreateResult(val, DataType.Decimal);
     }
     else if (IsNumeric(arg))
     {
         var val = ConvertUtil.GetValueDouble(arg);
         return CreateResult(val, DataType.Decimal);
     }
     else if (arg is string)
     {
         return CreateResult(0d, DataType.Decimal);
     }
     else if (arg is ExcelErrorValue)
     {
         return CreateResult(arg, DataType.ExcelError);
     }
     throw new ExcelErrorValueException(eErrorType.Value);
 }
Ejemplo n.º 14
0
 public override CompileResult Execute(IEnumerable<FunctionArgument> arguments, ParsingContext context)
 {
     ValidateArguments(arguments, 1);
     var number = ArgToInt(arguments, 0);
     ThrowExcelErrorValueExceptionIf(() => number < 1 || number > 255, eErrorType.Value);
     return CreateResult(((char) number).ToString(), DataType.String);
 }
Ejemplo n.º 15
0
Archivo: Sum.cs Proyecto: acinep/epplus
 private double Calculate(FunctionArgument arg, ParsingContext context)
 {
     var retVal = 0d;
     if (ShouldIgnore(arg))
     {
         return retVal;
     }
     if (arg.Value is IEnumerable<FunctionArgument>)
     {
         foreach (var item in (IEnumerable<FunctionArgument>)arg.Value)
         {
             retVal += Calculate(item, context);
         }
     }
     else if (arg.Value is ExcelDataProvider.IRangeInfo)
     {
         foreach (var c in (ExcelDataProvider.IRangeInfo)arg.Value)
         {
             if (ShouldIgnore(c, context) == false)
             {
                 CheckForAndHandleExcelError(c);
                 retVal += c.ValueDouble;
             }
         }
     }
     else
     {
         CheckForAndHandleExcelError(arg);
         retVal += ConvertUtil.GetValueDouble(arg.Value, true);
     }
     return retVal;
 }
Ejemplo n.º 16
0
        public override CompileResult Execute(IEnumerable<FunctionArgument> arguments, ParsingContext context)
        {
            var functionArguments = arguments as FunctionArgument[] ?? arguments.ToArray();
            ValidateArguments(functionArguments, 3);
            var sumRange = ArgsToDoubleEnumerable(true, new List<FunctionArgument> {functionArguments[0]}, context).ToList();
            var argRanges = new List<ExcelDataProvider.IRangeInfo>();
            var criterias = new List<object>();
            for (var ix = 1; ix < 31; ix += 2)
            {
                if (functionArguments.Length <= ix) break;
                var rangeInfo = functionArguments[ix].ValueAsRangeInfo;
                argRanges.Add(rangeInfo);
                if (ix > 1)
                {
                    ThrowExcelErrorValueExceptionIf(() => rangeInfo.GetNCells() != argRanges[0].GetNCells(), eErrorType.Value);
                }
                criterias.Add(functionArguments[ix + 1].Value);
            }
            IEnumerable<int> matchIndexes = GetMatchIndexes(argRanges[0], criterias[0]);
            var enumerable = matchIndexes as IList<int> ?? matchIndexes.ToList();
            for (var ix = 1; ix < argRanges.Count && enumerable.Any(); ix++)
            {
                var indexes = GetMatchIndexes(argRanges[ix], criterias[ix]);
                matchIndexes = enumerable.Intersect(indexes);
            }

            var result = matchIndexes.Sum(index => sumRange[index]);

            return CreateResult(result, DataType.Decimal);
        }
Ejemplo n.º 17
0
 public override CompileResult Execute(IEnumerable<FunctionArgument> arguments, ParsingContext context)
 {
     if (arguments == null || arguments.Count() == 0)
     {
         return CreateResult(false, DataType.Boolean);
     }
     foreach (var argument in arguments)
     {
         if (argument.Value is ExcelDataProvider.IRangeInfo)
         {
             var r = (ExcelDataProvider.IRangeInfo)argument.Value;
             if (ExcelErrorValue.Values.IsErrorValue(r.GetValue(r.Address._fromRow, r.Address._fromCol)))
             {
                 return CreateResult(true, DataType.Boolean);
             }
         }
         else
         {
             if (ExcelErrorValue.Values.IsErrorValue(argument.Value))
             {
                 return CreateResult(true, DataType.Boolean);
             }
         }                
     }
     return CreateResult(false, DataType.Boolean);
 }
Ejemplo n.º 18
0
 public override CompileResult Execute(IEnumerable<FunctionArgument> arguments, ParsingContext context)
 {
     var isError = new IsError();
     var result = isError.Execute(arguments, context);
     if ((bool) result.Result)
     {
         var arg = GetFirstValue(arguments);
         if (arg is ExcelDataProvider.IRangeInfo)
         {
             var r = (ExcelDataProvider.IRangeInfo)arg;
             var e=r.GetValue(r.Address._fromRow, r.Address._fromCol) as ExcelErrorValue;
             if (e !=null && e.Type==eErrorType.NA)
             {
                 return CreateResult(false, DataType.Boolean);
             }
         }
         else
         {
             if (arg is ExcelErrorValue && ((ExcelErrorValue)arg).Type==eErrorType.NA)
             {
                 return CreateResult(false, DataType.Boolean);
             }
         }
     }
     return result;
 }
Ejemplo n.º 19
0
 public override CompileResult Execute(IEnumerable<FunctionArgument> arguments, ParsingContext context)
 {
     ValidateArguments(arguments, 2);
     var args = arguments.ElementAt(0).Value as ExcelDataProvider.IRangeInfo; //IEnumerable<FunctionArgument>;
     var criteria = arguments.ElementAt(1).Value;
     ThrowExcelErrorValueExceptionIf(() => criteria == null || criteria.ToString().Length > 255, eErrorType.Value);
     var retVal = 0d;
     if (arguments.Count() > 2)
     {
         var sumRange = arguments.ElementAt(2).Value as ExcelDataProvider.IRangeInfo;//IEnumerable<FunctionArgument>;
         retVal = CalculateWithSumRange(args, criteria.ToString(), sumRange, context);
     }
     else
     {
         if (args != null)
         {
             retVal = CalculateSingleRange(args, criteria.ToString(), context);   
         }
         else
         {
             retVal = CalculateSingleRange((arguments.ElementAt(0).Value as IEnumerable<FunctionArgument>),
                                           criteria.ToString(), context);
         }
     }
     return CreateResult(retVal, DataType.Decimal);
 }
Ejemplo n.º 20
0
        public override CompileResult Compile(IEnumerable<Expression> children, ParsingContext context)
        {
            if (children.Count() != 2) return new CompileResult(eErrorType.Value);
            var args = new List<FunctionArgument>();
            Function.BeforeInvoke(context);
            var firstChild = children.First();
            var lastChild = children.ElementAt(1);
            try
            {
                var result = firstChild.Compile();
                if (result.DataType == DataType.ExcelError && (Equals(result.Result,
                    ExcelErrorValue.Create(eErrorType.NA))))
                {
                    args.Add(new FunctionArgument(lastChild.Compile().Result));
                }
                else
                {
                    args.Add(new FunctionArgument(result.Result));
                }

            }
            catch (ExcelErrorValueException)
            {
                args.Add(new FunctionArgument(lastChild.Compile().Result));
            }
            return Function.Execute(args, context);
        }
Ejemplo n.º 21
0
 public override CompileResult Execute(IEnumerable<FunctionArgument> arguments, ParsingContext context)
 {
     ValidateArguments(arguments, 2);
     var str = ArgToString(arguments, 0);
     var length = ArgToInt(arguments, 1);
     return CreateResult(str.Substring(0, length), DataType.String);
 }
Ejemplo n.º 22
0
 private void _CheckForAndHandleExcelError(ExcelDataProvider.ICellInfo cell, ParsingContext context)
 {
     if (context.Scopes.Current.IsSubtotal)
     {
         CheckForAndHandleExcelError(cell);
     }
 }
Ejemplo n.º 23
0
        private void Calculate(IEnumerable<FunctionArgument> items, ParsingContext context, ref double nItems)
        {
            foreach (var item in items)
            {
                var cs = item.Value as ExcelDataProvider.IRangeInfo;
                if (cs != null)
                {
                    foreach (var c in cs)
                    {
                        _CheckForAndHandleExcelError(c, context);
                        if (!ShouldIgnore(c, context) && ShouldCount(c.Value))
                        {
                            nItems++;
                        }
                    }
                }
                else if (item.Value is IEnumerable<FunctionArgument>)
                {
                    Calculate((IEnumerable<FunctionArgument>)item.Value, context, ref nItems);
                }
                else
                {
                    _CheckForAndHandleExcelError(item, context);
                    if (!ShouldIgnore(item) && ShouldCount(item.Value))
                    {
                        nItems++;
                    }
                }

            }
        }
Ejemplo n.º 24
0
 public override CompileResult Execute(IEnumerable<FunctionArgument> arguments, ParsingContext context)
 {
     if (arguments == null || arguments.Count() == 0)
     {
         return CreateResult(true, DataType.Boolean);
     }
     var result = true;
     foreach (var arg in arguments)
     {
         if (arg.Value is ExcelDataProvider.IRangeInfo)
         {                    
             var r=(ExcelDataProvider.IRangeInfo)arg.Value;
             if (r.GetValue(r.Address._fromRow, r.Address._fromCol) != null)
             {
                 result = false;
             }
         }
         else
         {
             if (arg.Value != null && (arg.Value.ToString() != string.Empty))
             {
                 result = false;
                 break;
             }
         }
     }
     return CreateResult(result, DataType.Boolean);
 }
 public override void Execute(ParsingContext context)
 {
     var savedParserInput = context.CurrentParserInput;
     context.CurrentParserInput = GetResultNode(context);
     CompleteReduce(context);
     context.CurrentParserInput = savedParserInput;
 }
Ejemplo n.º 26
0
        public override LinkedList<IWikiElement> Parse(ParsingContext parsingContext, ElementContent containerContent)
        {
            var elements = new LinkedList<IWikiElement>();

            foreach (Match match in _linkExpression.Matches(containerContent.ToString()))
            {
                var elementContent = new ElementContent(containerContent, match);
                var innerContent = new ElementContent(containerContent, match.Groups["content"]);

                string originalAddress, normalizedAddress;

                if (match.Groups["url"].Success)
                {
                    originalAddress = match.Groups["url"].Value;
                    normalizedAddress = FormatUrl(originalAddress);
                }
                else if (match.Groups["email"].Success)
                {
                    originalAddress = match.Groups["email"].Value;
                    normalizedAddress = FormatEmail(originalAddress);
                }
                else
                    continue;

                string text = match.Groups["text"].Success ? match.Groups["text"].Value : originalAddress;
                bool noFollow = match.Groups["nofollow"].Success;

                var element = new LinkElement(parsingContext, elementContent, innerContent, normalizedAddress, text, noFollow);

                elements.AddLast(element);
            }

            return elements;
        }
Ejemplo n.º 27
0
 public override CompileResult Execute(IEnumerable<FunctionArgument> arguments, ParsingContext context)
 {
     ValidateArguments(arguments, 1);
     var firstArg = arguments.ElementAt(0);
     if (firstArg.Value == null || firstArg.ValueIsExcelError) return CreateResult(false, DataType.Boolean);
     return CreateResult(!(firstArg.Value is string), DataType.Boolean);
 }
Ejemplo n.º 28
0
 private void _CheckForAndHandleExcelError(FunctionArgument arg, ParsingContext context)
 {
     if (context.Scopes.Current.IsSubtotal)
     {
         CheckForAndHandleExcelError(arg);
     }
 }
Ejemplo n.º 29
0
 public override CompileResult Execute(IEnumerable<FunctionArgument> arguments, ParsingContext context)
 {
     ValidateArguments(arguments, 1);
     var error = arguments.ElementAt(0);
     var isErrorFunc = context.Configuration.FunctionRepository.GetFunction("iserror");
     var isErrorResult = isErrorFunc.Execute(arguments, context);
     if (!(bool) isErrorResult.Result)
     {
         return CreateResult(ExcelErrorValue.Create(eErrorType.NA), DataType.ExcelError);
     }
     var errorType = error.ValueAsExcelErrorValue;
     int retValue;
     switch (errorType.Type)
     {
         case eErrorType.Null:
             return CreateResult(1, DataType.Integer);
         case eErrorType.Div0:
             return CreateResult(2, DataType.Integer);
         case eErrorType.Value:
             return CreateResult(3, DataType.Integer);
         case eErrorType.Ref:
             return CreateResult(4, DataType.Integer);
         case eErrorType.Name:
             return CreateResult(5, DataType.Integer);
         case eErrorType.Num:
             return CreateResult(6, DataType.Integer);
         case eErrorType.NA:
             return CreateResult(7, DataType.Integer);
     }
     return CreateResult(ExcelErrorValue.Create(eErrorType.NA), DataType.ExcelError);
 }
Ejemplo n.º 30
0
 public override CompileResult Execute(IEnumerable<FunctionArgument> arguments, ParsingContext context)
 {
     ValidateArguments(arguments, 1);
     var dateObj = arguments.ElementAt(0).Value;
     System.DateTime date = ParseDate(arguments, dateObj);
     return CreateResult(date.Second, DataType.Integer);
 }
Ejemplo n.º 31
0
 public override CompileResult Execute(IEnumerable <FunctionArgument> arguments, ParsingContext context)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 32
0
        public override CompileResult Execute(IEnumerable <FunctionArgument> arguments, ParsingContext context)
        {
            ValidateArguments(arguments, 1);
            var firstArg = arguments.First();

            return(GetResultByObject(firstArg.Value));
        }
Ejemplo n.º 33
0
        public override CompileResult Execute(IEnumerable <FunctionArgument> arguments, ParsingContext context)
        {
            ValidateArguments(arguments, 1);
            var arg = ArgToDecimal(arguments, 0);

            return(CreateResult(MathHelper.HArcsin(arg), DataType.Decimal));
        }
Ejemplo n.º 34
0
        public override CompileResult Execute(IEnumerable <FunctionArgument> arguments, ParsingContext context)
        {
            if (this.ArgumentsAreValid(arguments, 2, out eErrorType argumentError) == false)
            {
                return(new CompileResult(argumentError));
            }
            var items = new List <object>();

            for (int x = 0; x < arguments.Count(); x++)
            {
                items.Add(arguments.ElementAt(x).ValueFirst);
            }

            var chooseIndeces = arguments.ElementAt(0).ValueFirst as IEnumerable <FunctionArgument>;

            if (chooseIndeces != null && chooseIndeces.Count() > 1)
            {
                IntArgumentParser intParser = new IntArgumentParser();
                object[]          values    = chooseIndeces.Select(chosenIndex => items[(int)intParser.Parse(chosenIndex.ValueFirst)]).ToArray();
                return(CreateResult(values, DataType.Enumerable));
            }
            else
            {
                var index = ArgToInt(arguments, 0);
                return(CreateResult(items[index].ToString(), DataType.String));
            }
        }
Ejemplo n.º 35
0
        public override CompileResult Execute(IEnumerable <FunctionArgument> arguments, ParsingContext context)
        {
            ValidateArguments(arguments, 3);
            var text        = ArgToString(arguments, 0);
            var find        = ArgToString(arguments, 1);
            var replaceWith = ArgToString(arguments, 2);
            var result      = text.Replace(find, replaceWith);

            return(CreateResult(result, DataType.String));
        }
Ejemplo n.º 36
0
        public override CompileResult Execute(IEnumerable <FunctionArgument> arguments, ParsingContext context)
        {
            ValidateArguments(arguments, 4);
            var rate         = ArgToDecimal(arguments, 0);
            var per          = ArgToInt(arguments, 1);
            var nPer         = ArgToInt(arguments, 2);
            var presentValue = ArgToDecimal(arguments, 3);
            var fv           = 0d;

            if (arguments.Count() >= 5)
            {
                fv = ArgToDecimal(arguments, 4);
            }
            var type = PmtDue.EndOfPeriod;

            if (arguments.Count() >= 6)
            {
                type = (PmtDue)ArgToInt(arguments, 5);
            }
            var result = IPmtImpl.Ipmt(rate, per, nPer, presentValue, fv, type);

            if (result.HasError)
            {
                return(CreateResult(result.ExcelErrorType));
            }
            return(CreateResult(result.Result, DataType.Decimal));
        }
Ejemplo n.º 37
0
 public override CompileResult Compile(IEnumerable <Expression> children, ParsingContext context)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 38
0
 public override ParsingResult?TryParse(ParsingContext parsingContext) => _sequence.TryParse(parsingContext);
Ejemplo n.º 39
0
        public override CompileResult Execute(IEnumerable <FunctionArgument> arguments, ParsingContext context)
        {
            if (this.ArgumentsAreValid(arguments, 4, out eErrorType argumentError) == false)
            {
                return(new CompileResult(argumentError));
            }
            var oldText         = ArgToString(arguments, 0);
            var startPos        = ArgToInt(arguments, 1);
            var nCharsToReplace = ArgToInt(arguments, 2);
            var newText         = ArgToString(arguments, 3);
            var firstPart       = GetFirstPart(oldText, startPos);
            var lastPart        = GetLastPart(oldText, startPos, nCharsToReplace);
            var result          = string.Concat(firstPart, newText, lastPart);

            return(CreateResult(result, DataType.String));
        }
Ejemplo n.º 40
0
        public ParserTests()
        {
            var functionService = new FunctionService(new Random());

            _parsingContext = new ParsingContext(new StatService(functionService), functionService);
        }
Ejemplo n.º 41
0
        public override Token TryMatch(ParsingContext context, ISourceStream source)
        {
            try
            {
                var text = source.Text;
                switch (_Kind)
                {
                case EDateTimeKind.Date:
                    return(source.CreateToken(this.OutputTerminal, DateTime.Parse(PreivewDate(source))));

                case EDateTimeKind.TimeOfDay:
                    return(source.CreateToken(this.OutputTerminal, DateTime.Parse(PreivewTime(source))));

                case EDateTimeKind.DateTime:
                {
                    var date = PreivewDate(source);
                    source.IsChar('T');
                    var time = PreivewTime(source, source.PreviewPosition);
                    return(source.CreateToken(this.OutputTerminal, DateTime.Parse(date + " " + time)));
                }

                case EDateTimeKind.DateTimeOffset:
                {
                    var date = PreivewDate(source);
                    source.IsChar('T');
                    var time = PreivewTime(source, source.PreviewPosition);
                    if (source.PreviewChar == '+' || source.PreviewChar == '-')
                    {
                        var zone = PreviewZone(source, source.PreviewPosition);
                        return(source.CreateToken(this.OutputTerminal, DateTime.Parse(date + " " + time + " " + zone)));
                    }
                    else
                    {
                        source.IsChar('Z');
                    }
                    return(source.CreateToken(this.OutputTerminal, DateTime.Parse(date + " " + time)));
                }

                case EDateTimeKind.TimeSpan:
                {
                    var multi = source.PreviewChar == '-' ? -1 : 1;
                    if (source.PreviewChar == '+')
                    {
                        source.Position++;
                    }
                    source.IsChar('P');
                    var day = PreviewDigit(source);
                    source.IsChar('D');
                    var space = TimeSpan.FromDays(Convert.ToDouble(day) * multi);
                    if (source.PreviewChar == 'T')
                    {
                        source.PreviewPosition++;
                        var iscontinue = true;
                        do
                        {
                            var val = PreviewDigit(source);
                            switch (source.PreviewChar)
                            {
                            case 'H':
                                space += TimeSpan.FromHours(Convert.ToDouble(val) * multi);
                                break;

                            case 'M':
                                space += TimeSpan.FromMinutes(Convert.ToDouble(val) * multi);
                                break;

                            case 'S':
                                space += TimeSpan.FromSeconds(Convert.ToDouble(val) * multi);
                                break;

                            default:
                                iscontinue = false;
                                break;
                            }
                            if (iscontinue)
                            {
                                source.PreviewPosition++;
                            }
                        } while (iscontinue && Char.IsDigit(source.PreviewChar));
                    }
                    return(source.CreateToken(this.OutputTerminal, space));
                }

                default:
                    return(context.CreateErrorToken("not suppored datetimekind."));
                }
            }
            catch (Exception ex)
            {
                return(null);
            }
        }
Ejemplo n.º 42
0
 public static LookupNavigator Create(LookupDirection direction, LookupArguments args, ParsingContext parsingContext)
 {
     if (args.ArgumentDataType == LookupArguments.LookupArgumentDataType.ExcelRange)
     {
         return(new ExcelLookupNavigator(direction, args, parsingContext));
     }
     else if (args.ArgumentDataType == LookupArguments.LookupArgumentDataType.DataArray)
     {
         return(new ArrayLookupNavigator(direction, args, parsingContext));
     }
     throw new NotSupportedException("Invalid argument datatype");
 }
Ejemplo n.º 43
0
 /// <summary>
 /// The create type name from token ast.
 /// </summary>
 /// <param name="parsingcontext">
 /// </param>
 /// <param name="node">
 /// </param>
 protected static void CreateTypeNameFromTokenAst(ParsingContext parsingcontext, ParseTreeNode node)
 {
     CreateTypeFromTokenAst <TypeName>(parsingcontext, node);
 }
Ejemplo n.º 44
0
        public override CompileResult Execute(IEnumerable <FunctionArgument> arguments, ParsingContext context)
        {
            var result = System.Math.Round((double)System.Math.PI, 14);

            return(CreateResult(result, DataType.Decimal));
        }
Ejemplo n.º 45
0
 /// <summary>
 /// The create rank specifier ast.
 /// </summary>
 /// <param name="parsingcontext">
 /// </param>
 /// <param name="node">
 /// </param>
 protected static void CreateRankSpecifierAst(ParsingContext parsingcontext, ParseTreeNode node)
 {
     // [0]      [1]       [2]
     // "[" + expression + "]";
     node.AstNode = node.ChildNodes[1].AstNode;
 }
Ejemplo n.º 46
0
        /// <summary>
        /// The create variable group raw ast.
        /// </summary>
        /// <param name="parsingContext">
        /// </param>
        /// <param name="node">
        /// </param>
        protected static void CreateVariableGroupRawAst(ParsingContext parsingContext, ParseTreeNode node)
        {
            var var = Ast <Variable>(node);

            //// [0]                             [1]
            // declaration_specifiers + variable_declarator_list.Q()  + ";";
            var declarationSpecifiers = (Tuple <Qualifier, TypeBase>)node.ChildNodes[0].AstNode;

            var.Qualifiers = declarationSpecifiers.Item1;
            var.Type       = declarationSpecifiers.Item2;

            var declarators = GetOptional <List <Variable> >(node.ChildNodes[1]);

            if (declarators != null)
            {
                var.SubVariables = declarators;

                // Update array type for sub variables
                foreach (var subVariable in declarators)
                {
                    if (subVariable.Type is ArrayType)
                    {
                        ((ArrayType)subVariable.Type).Type = var.Type;
                    }
                    else
                    {
                        subVariable.Type = var.Type;
                    }
                }
            }

            // If this is a variable group, check if we can transform it to a single variable declaration.
            if (var.IsGroup)
            {
                // If the variable is a single variable declaration, replace the group
                if (var.SubVariables.Count == 1)
                {
                    var subVariable = var.SubVariables[0];
                    subVariable.MergeFrom(var);
                    node.AstNode = subVariable;
                }
            }
            else
            {
                // If variable declarators is 0, check if this is a named struct
                var.Type.Qualifiers = var.Qualifiers;
                if (var.Type is StructType)
                {
                    node.AstNode = var.Type;
                }
                else if (var.Type is InterfaceType)
                {
                    node.AstNode = var.Type;
                }
                else if (var.Type is ClassType)
                {
                    node.AstNode = var.Type;
                }
                else
                {
                    parsingContext.AddParserError("Expecting identifier for variable declaration [{0}]", var.Type);
                }

                if (var.Type.Name == null)
                {
                    parsingContext.AddParserError("Cannot declare anonymous type at the top level");
                }
            }
        }
Ejemplo n.º 47
0
 /// <summary>
 /// The create method declaration ast.
 /// </summary>
 /// <param name="context">
 /// </param>
 /// <param name="node">
 /// </param>
 protected static void CreateMethodDeclarationAst(ParsingContext context, ParseTreeNode node)
 {
     //// method_declaration_raw + ";";
     node.AstNode = node.ChildNodes[0].AstNode;
 }
Ejemplo n.º 48
0
        /// <summary>
        /// The create type name ast.
        /// </summary>
        /// <param name="parsingcontext">
        /// </param>
        /// <param name="node">
        /// </param>
        protected static void CreateTypeNameAst(ParsingContext parsingcontext, ParseTreeNode node)
        {
            var value = Ast <TypeName>(node);

            value.Name = (Identifier)node.ChildNodes[0].AstNode;
        }
Ejemplo n.º 49
0
        /// <summary>
        /// The create identifier list ast.
        /// </summary>
        /// <param name="parsingcontext">
        /// </param>
        /// <param name="node">
        /// </param>
        protected static void CreateIdentifierListAst(ParsingContext parsingcontext, ParseTreeNode node)
        {
            var identifiers = Ast <List <Identifier> >(node);

            FillListFromNodes(node.ChildNodes, identifiers);
        }
Ejemplo n.º 50
0
 protected static void CreateQualifiersAst(ParsingContext context, ParseTreeNode node)
 {
     node.AstNode = CollectQualifiers(node.ChildNodes[0]);
 }
Ejemplo n.º 51
0
        /// <summary>
        /// The create declaration statement ast.
        /// </summary>
        /// <param name="context">
        /// </param>
        /// <param name="node">
        /// </param>
        protected static void CreateDeclarationStatementAst(ParsingContext context, ParseTreeNode node)
        {
            var declarationStatement = Ast <DeclarationStatement>(node);

            declarationStatement.Content = (Node)node.ChildNodes[0].AstNode;
        }
Ejemplo n.º 52
0
        /// <summary>
        /// The create literal expression ast.
        /// </summary>
        /// <param name="parsingcontext">
        /// </param>
        /// <param name="node">
        /// </param>
        protected static void CreateLiteralExpressionAst(ParsingContext parsingcontext, ParseTreeNode node)
        {
            var value = Ast <LiteralExpression>(node);

            value.Literal = (Literal)node.ChildNodes[0].AstNode;
        }
Ejemplo n.º 53
0
        public override CompileResult Execute(IEnumerable <FunctionArgument> arguments, ParsingContext context)
        {
            ValidateArguments(arguments, 1);
            var val = ArgToDecimal(arguments, 0);

            if (val < 0)
            {
                val *= -1;
            }
            return(CreateResult(val, DataType.Decimal));
        }
Ejemplo n.º 54
0
 protected static void CreateEmptyStatementAst(ParsingContext context, ParseTreeNode node)
 {
     Ast <EmptyStatement>(node);
 }
Ejemplo n.º 55
0
        public override CompileResult Execute(IEnumerable <FunctionArgument> arguments, ParsingContext context)
        {
            ValidateArguments(arguments, 2);
            var val1 = arguments.ElementAt(0).ValueFirst;
            var val2 = arguments.ElementAt(1).ValueFirst;

            if (val1 == null && val2 == null)
            {
                return(CreateResult(true, DataType.Boolean));
            }
            else if ((val1 == null && val2 != null) || (val1 != null && val2 == null))
            {
                return(CreateResult(false, DataType.Boolean));
            }

            var result = string.Compare(val1.ToString(), val2.ToString(), StringComparisonEx.InvariantCulture);

            return(CreateResult(result == 0, DataType.Boolean));
        }
Ejemplo n.º 56
0
 /// <summary>
 /// The create assignment operator.
 /// </summary>
 /// <param name="parsingContext">
 /// </param>
 /// <param name="node">
 /// </param>
 protected static void CreateAssignmentOperator(ParsingContext parsingContext, ParseTreeNode node)
 {
     node.AstNode = AssignmentOperatorHelper.FromString(node.ChildNodes[0].Token.Text);
 }
Ejemplo n.º 57
0
        public override CompileResult Execute(IEnumerable <FunctionArgument> arguments, ParsingContext context)
        {
            ValidateArguments(arguments, 2);
            var number = ArgToDecimal(arguments, 0);
            var power  = ArgToDecimal(arguments, 1);
            var result = System.Math.Pow(number, power);

            return(CreateResult(result, DataType.Decimal));
        }
Ejemplo n.º 58
0
 internal override IParsingResult Parse(ParsingContext context)
 {
     return(Parsers.MangledName.Parse(context));
 }
Ejemplo n.º 59
0
        public virtual IEnumerable <string> GetReferencedAddresses(string cellFormula, ParsingContext context)
        {
            var resultCells = new List <string>();
            var r           = context.Configuration.Lexer.Tokenize(cellFormula, context.Scopes.Current.Address.Worksheet);
            var toAddresses = r.Where(x => x.TokenTypeIsSet(TokenType.ExcelAddress));

            foreach (var toAddress in toAddresses)
            {
                var rangeAddress = context.RangeAddressFactory.Create(toAddress.Value);
                var rangeCells   = new List <string>();
                if (rangeAddress.FromRow < rangeAddress.ToRow || rangeAddress.FromCol < rangeAddress.ToCol)
                {
                    for (var col = rangeAddress.FromCol; col <= rangeAddress.ToCol; col++)
                    {
                        for (var row = rangeAddress.FromRow; row <= rangeAddress.ToRow; row++)
                        {
                            resultCells.Add(context.RangeAddressFactory.Create(col, row).Address);
                        }
                    }
                }
                else
                {
                    rangeCells.Add(toAddress.Value);
                }
                resultCells.AddRange(rangeCells);
            }
            return(resultCells);
        }
Ejemplo n.º 60
0
Archivo: Acos.cs Proyecto: nxoxn/EPPlus
        /// <summary>
        /// Calculate the Arccosine of a given input.
        /// </summary>
        /// <param name="arguments">Input to have its Arccosine calculated.</param>
        /// <param name="context">Unused, this is information about where the function is being executed.</param>
        /// <returns>Returns the Arccosine of a number.</returns>
        public override CompileResult Execute(IEnumerable <FunctionArgument> arguments, ParsingContext context)
        {
            if (this.ArgumentCountIsValid(arguments, 1) == false)
            {
                return(new CompileResult(eErrorType.Value));
            }
            var argument = arguments.First().Value;

            if (!ConvertUtil.TryParseObjectToDecimal(argument, out double result))
            {
                return(new CompileResult(eErrorType.Value));
            }
            return(this.CreateResult(System.Math.Acos(result), DataType.Decimal));
        }