diff --git a/src/client/spark_excel/algogen/CellRef.cs b/src/client/spark_excel/algogen/CellRef.cs new file mode 100644 index 000000000..268b4cf3f --- /dev/null +++ b/src/client/spark_excel/algogen/CellRef.cs @@ -0,0 +1,239 @@ +using System; +using System.Diagnostics; +using System.Text; + +namespace bts.excel +{ + /// + /// Defines a reference to some Cell instance, whether it exists or not. + /// + /// + /// Static methods are provided for conversion of column names etc. + /// + public sealed class CellRef : IComparable, IComparable + { + /// + /// Constructor for the class: CellRef + /// + /// Name of the sheet where the cell belongs. + /// Coordinate (column, row) for the cell in the sheet. + public CellRef(string sheetName, (int col1, int row1) coordinate) + { + SheetName = sheetName; + Coordinate = coordinate; + LocalAddress = ConvertCoordToAddress(coordinate); + } + + /// + /// Maximum number of rows, to e compatible with Excel. + /// + private const int MaxRows = 1048576; + + /// + /// Maximum number of columns, to be compatible with Excel. + /// + private const int MaxColumns = 16384; + + // NOTE: Worksheet and workbook specifications and limits + // http://office.microsoft.com/en-gb/excel-help/excel-specifications-and-limits-HP010342495.aspx + // + // Worksheet size: 1,048,576 rows by 16,384 columns. + // * 1048575 is the highest number representable in 20 bits. + // * 16383 is the highest number representable in 14 bits. That leaves 2 spare bits in a 16-bit word. + // Column width: 255 characters (I'm not sure what the real significance of this is). + // Total number of characters that a cell can contain: 32,767 characters + // * 32766 is the highest number representable in 15 bits. That leaves 1 spare bit in a 16-bit word. + // + + /// + /// Name of the sheet where the cell belongs. + /// + /// + /// All cells belong to some Sheet instance, so this name must never be null or empty. + /// + public string SheetName { get; } + + /// + /// Coordinate (column, row) for the cell in the sheet. + /// + public (int col1, int row1) Coordinate { get; } + + public CellRef Offset(int columnOffset, int rowOffset) + { + return new CellRef(SheetName, (Column + columnOffset, Row + rowOffset)); + } + + public int Column => Coordinate.col1; + + public int Row => Coordinate.row1; + + public string LocalAddress { get; internal set; } + + #region Address conversion + + /// + /// Converts a column identifier, using letters, to a column number. + /// + /// Column identifier using letters. + /// Column number. + /// When column number exceeds maximum. + public static int ConvertToColumnNumber(string columnName) + { + var number = 0; + var pow = 1; + for (var i = columnName.Length - 1; i >= 0; i--) + { + number += (columnName[i] - 'A' + 1) * pow; + pow *= 26; + } + + if (number > MaxColumns) + { + throw new ArgumentOutOfRangeException(nameof(columnName), + "Column number from columnName exceeds maximum"); + } + + return number; + } + + /// + /// Converts a column number to a column identifier using letters. + /// + /// Column number. + /// Column identifier using letters. + /// When column number is invalid. + public static string ConvertToColumnName(int columnNumber) + { + if (columnNumber < 1 || columnNumber > MaxColumns) + { + throw new ArgumentOutOfRangeException(nameof(columnNumber), + "Invalid column number"); + } + + var dividend = columnNumber; + var columnName = string.Empty; + while (dividend > 0) + { + var modulo = (dividend - 1) % 26; + columnName = Convert.ToChar(65 + modulo) + columnName; + dividend = (dividend - modulo) / 26; + } + + return columnName; + } + + /// + /// Converts an address, like "A1", to a cell coordinate. + /// + /// Cell address, like "A1". + /// Coordinate of cell on sheet. + /// When address argument is null. + /// When address is invalid. + public static (int col1, int row1) ConvertAddressToCoord(string address) + { + if (address == null) + { + throw new ArgumentNullException(nameof(address)); + } + + address = address.Replace("$", string.Empty); + address = address.ToUpper(); + + var letters = new StringBuilder(); + foreach (var c in address) + { + if (c < 'A' || c > 'Z') + { + break; + } + letters.Append(c); + } + + if (letters.Length == 0 || letters.Length > 3) + { + throw new ArgumentException( + "Column name requires 1 to 3 letters", + nameof(address)); + } + + var numbers = address.Substring(letters.Length); + if (numbers.Length == 0) + { + throw new ArgumentException("Row number is required", nameof(address)); + } + + Debug.Assert(letters.Length + numbers.Length == address.Length); + + var row1 = int.Parse(numbers); + var col1 = ConvertToColumnNumber(letters.ToString()); + + return (col1, row1); + } + + /// + /// Convert cell coordinate to cell address, like "A1". + /// + /// Coordinate of cell on sheet. + /// Provide absolute address, like "$A$1". + /// Cell address, like "A1", or optionally like "$A$1". + /// + public static string ConvertCoordToAddress((int col1, int row1) coordinate, bool absolute = false) + { + if (coordinate.row1 < 1 || coordinate.row1 > MaxRows || + coordinate.col1 < 1 || coordinate.col1 > MaxColumns) + { + throw new ArgumentOutOfRangeException(nameof(coordinate), + "Invalid coordinate"); + } + + var (col1, row1) = coordinate; + return absolute + ? $"${ConvertToColumnName(col1)}${row1}" + : $"{ConvertToColumnName(col1)}{row1}"; + } + + #endregion + + #region IComparable + + public int CompareTo(CellRef other) + { + if (other == null) return -1; + return string.Compare(ToString(), other.ToString(), + StringComparison.Ordinal); + } + + public int CompareTo(object obj) + { + if (obj.GetType() != GetType()) return -1; + return CompareTo((CellRef)obj); + } + + #endregion + + #region HashCode & Equals + + /// Unique key + public override string ToString() + { + return $"'{SheetName}'!{LocalAddress}"; + } + + public override int GetHashCode() + { + return ToString().GetHashCode(); + } + + public override bool Equals(object obj) + { + if (obj == null) return false; + + if (obj != null && !(obj is CellRef)) + throw new ArgumentException("Object must be of type CellRef."); + + return GetHashCode().Equals(obj.GetHashCode()); + } + + #endregion + } +} \ No newline at end of file diff --git a/src/client/spark_excel/algogen/Expression.cs b/src/client/spark_excel/algogen/Expression.cs deleted file mode 100644 index 932ecd4c3..000000000 --- a/src/client/spark_excel/algogen/Expression.cs +++ /dev/null @@ -1,22 +0,0 @@ -using LibWorkbooks.LibDep; -using LibWorkbooks.Parser; - -namespace spark.excel -{ - internal class Expression : IExpression - { - private readonly FormulaParser.ExprContext _context; - private readonly EvaluationVisitor _visitor; - - public Expression(FormulaParser.ExprContext context, EvaluationVisitor visitor) - { - _context = context; - _visitor = visitor; - } - - public object Evaluate() - { - return _context.Accept(_visitor); - } - } -} \ No newline at end of file diff --git a/src/client/spark_excel/algogen/Generate.cs b/src/client/spark_excel/algogen/Generate.cs index d6af4f24e..af2c61ec9 100644 --- a/src/client/spark_excel/algogen/Generate.cs +++ b/src/client/spark_excel/algogen/Generate.cs @@ -36,16 +36,16 @@ namespace bts.excel //https://stackoverflow.com/questions/31511610/antlr-source-to-target-language-conversion public class Generate { - static ConcurrentDictionary _cache = new ConcurrentDictionary(); - [ExcelFunction(IsMacroType = true)] static public string bts_generate_code_from_sink(string name, [ExcelArgument(AllowReference=true)] object sink) { ExcelReference rref = (ExcelReference)sink; - var form = XlCall.Excel(XlCall.xlfGetCell, 41, rref); + var formula = XlCall.Excel(XlCall.xlfGetCell, 41, rref); + + string sheetname = (string)XlCall.Excel(XlCall.xlSheetNm, rref); //var formabs = XlCall.Excel(XlCall.xlfFormulaConvert, form, ExcelDna. - var antlrstream = new AntlrInputStream(form.ToString()); + var antlrstream = new AntlrInputStream(formula.ToString()); var lexer = new ExcelFormulaLexer(antlrstream); var tokens = new CommonTokenStream(lexer); var parser = new ExcelFormulaParser(tokens); @@ -59,7 +59,7 @@ namespace bts.excel throw new ExcelFormulaException(error_listener.ErrorLocation, error_listener.ErrorMessage); //AbstractParseTreeVisitor - ExcelFormulaBaseVisitor visitor = new ExcelFormulaBaseVisitor(); + GeneratorVisitor visitor = new GeneratorVisitor(rref, sheetname); visitor.VisitMain(parsetree); return parsetree.ToString(); diff --git a/src/client/spark_excel/algogen/GeneratorVisitor.cs b/src/client/spark_excel/algogen/GeneratorVisitor.cs index 02d261fc8..530ea7a1d 100644 --- a/src/client/spark_excel/algogen/GeneratorVisitor.cs +++ b/src/client/spark_excel/algogen/GeneratorVisitor.cs @@ -4,28 +4,29 @@ using System.Collections.ObjectModel; using System.Diagnostics; using spark_excel.grammar; +using ExcelDna.Integration; +using Excel = Microsoft.Office.Interop.Excel; + namespace bts.excel { internal class GeneratorVisitor : ExcelFormulaBaseVisitor - { - public GeneratorVisitor() + { + ExcelReference _ref; + string _sheetname; + public GeneratorVisitor(ExcelReference rref, string sheetname) { + _ref = rref; + _sheetname = sheetname; } - private static readonly object FunctionEvaluationLock = new object(); - - private FunctionLibrary FunctionLibrary => Workbook.FunctionLibrary; - - private ReadOnlyDictionary Functions => FunctionLibrary.Functions; - #region Context visitors overrides - public override object VisitMain(FormulaParser.MainContext context) + public override object VisitMain(ExcelFormulaParser.MainContext context) { return context.expr().Accept(this); } - public override object VisitCellList(FormulaParser.CellListContext context) + public override object VisitCellList(ExcelFormulaParser.CellListContext context) { var result = new List(); @@ -53,7 +54,7 @@ namespace bts.excel return result; } - public override object VisitMulDiv(FormulaParser.MulDivContext context) + public override object VisitMulDiv(ExcelFormulaParser.MulDivContext context) { var expr = context.expr(); @@ -97,7 +98,7 @@ namespace bts.excel : n1 / n2; } - public override object VisitAddSub(FormulaParser.AddSubContext context) + public override object VisitAddSub(ExcelFormulaParser.AddSubContext context) { var expr = context.expr(); @@ -152,7 +153,7 @@ namespace bts.excel : n1 - n2; } - public override object VisitPercentage(FormulaParser.PercentageContext context) + public override object VisitPercentage(ExcelFormulaParser.PercentageContext context) { var expr = context.expr(); @@ -166,7 +167,7 @@ namespace bts.excel return n1 / 100; } - public override object VisitRelational(FormulaParser.RelationalContext context) + public override object VisitRelational(ExcelFormulaParser.RelationalContext context) { var expr = context.expr(); @@ -200,23 +201,23 @@ namespace bts.excel } } - public override object VisitError(FormulaParser.ErrorContext context) + public override object VisitError(ExcelFormulaParser.ErrorContext context) { return new ErrorValue(context.GetText()); } - public override object VisitString(FormulaParser.StringContext context) + public override object VisitString(ExcelFormulaParser.StringContext context) { var str = context.GetText(); return str.Substring(1, str.Length - 2); } - public override object VisitRange(FormulaParser.RangeContext context) + public override object VisitRange(ExcelFormulaParser.RangeContext context) { return context.rng().Accept(this); } - public override object VisitUnary(FormulaParser.UnaryContext context) + public override object VisitUnary(ExcelFormulaParser.UnaryContext context) { var expr = context.expr(); @@ -231,7 +232,7 @@ namespace bts.excel return context.sign.Text == "-" ? -n1 : n1; } - public override object VisitName(FormulaParser.NameContext context) + public override object VisitName(ExcelFormulaParser.NameContext context) { var name = context.GetText(); @@ -248,7 +249,7 @@ namespace bts.excel return ErrorValue.Name; } - public override object VisitFunction(FormulaParser.FunctionContext context) + public override object VisitFunction(ExcelFormulaParser.FunctionContext context) { var name = context.name.Text; @@ -296,17 +297,17 @@ namespace bts.excel return args.HasResult ? args.Result : null; } - public override object VisitParenthesis(FormulaParser.ParenthesisContext context) + public override object VisitParenthesis(ExcelFormulaParser.ParenthesisContext context) { return context.expr().Accept(this); } - public override object VisitNumber(FormulaParser.NumberContext context) + public override object VisitNumber(ExcelFormulaParser.NumberContext context) { return Convert.ToDouble(context.GetText()); } - public override object VisitConcatenate(FormulaParser.ConcatenateContext context) + public override object VisitConcatenate(ExcelFormulaParser.ConcatenateContext context) { var expr = context.expr(); @@ -325,7 +326,7 @@ namespace bts.excel return $"{arg1}{arg2}"; } - public override object VisitPow(FormulaParser.PowContext context) + public override object VisitPow(ExcelFormulaParser.PowContext context) { var expr = context.expr(); @@ -364,7 +365,7 @@ namespace bts.excel return Math.Pow(n1, n2); } - public override object VisitRangeList(FormulaParser.RangeListContext context) + public override object VisitRangeList(ExcelFormulaParser.RangeListContext context) { var result = new List(); @@ -391,7 +392,7 @@ namespace bts.excel return result; } - public override object VisitEquality(FormulaParser.EqualityContext context) + public override object VisitEquality(ExcelFormulaParser.EqualityContext context) { var expr = context.expr(); @@ -436,17 +437,17 @@ namespace bts.excel return EvaluateEquality(context.op.Text, n1, n2); } - public override object VisitBoolean(FormulaParser.BooleanContext context) + public override object VisitBoolean(ExcelFormulaParser.BooleanContext context) { return Convert.ToBoolean(context.GetText().ToLower()); } - public override object VisitCell(FormulaParser.CellContext context) + public override object VisitCell(ExcelFormulaParser.CellContext context) { return context.@ref().Accept(this); } - public override object VisitCellRef(FormulaParser.CellRefContext context) + public override object VisitCellRef(ExcelFormulaParser.CellRefContext context) { // Column and row number for the cell. var colRow = context.colRow.Text; @@ -489,7 +490,7 @@ namespace bts.excel return new CellRef(sheet.Name, (col1, row1)); } - public override object VisitRangeRef(FormulaParser.RangeRefContext context) + public override object VisitRangeRef(ExcelFormulaParser.RangeRefContext context) { var obj = context.@ref().Accept(this); diff --git a/src/client/spark_excel/algogen/functions/lib/funcs/Average.cs b/src/client/spark_excel/algogen/functions/lib/funcs/Average.cs index 91dacbe57..289ec8776 100644 --- a/src/client/spark_excel/algogen/functions/lib/funcs/Average.cs +++ b/src/client/spark_excel/algogen/functions/lib/funcs/Average.cs @@ -1,9 +1,8 @@ using System; using System.Collections.Generic; using System.Linq; -using LibWorkbooks.LibDep; -namespace LibWorkbooks.StandardFunctions +namespace bts.excel.functions { public class Average { diff --git a/src/client/spark_excel/grammar/ExcelToC.stg b/src/client/spark_excel/grammar/ExcelToC.stg deleted file mode 100644 index 52ca81994..000000000 --- a/src/client/spark_excel/grammar/ExcelToC.stg +++ /dev/null @@ -1,8 +0,0 @@ -import "C.g4" - -functionSpecifier(globals,functions) ::= << -class Wrapper { - - -} ->> \ No newline at end of file diff --git a/src/client/spark_excel/spark_excel.csproj b/src/client/spark_excel/spark_excel.csproj index 128758d1c..3650118d4 100644 --- a/src/client/spark_excel/spark_excel.csproj +++ b/src/client/spark_excel/spark_excel.csproj @@ -66,14 +66,20 @@ + + + true + false + +