protected BindAttributeBase(BindScope bindingScope, ConditionSource conditionSource, ConditionComparer conditionComparer, object conditionTarget) : this(bindingScope) { ConditionSource = conditionSource; ConditionComparer = conditionComparer; ConditionTarget = conditionTarget; }
public override int Compare(Account left, Account right) { if (left == null) { throw new ArgumentNullException("left"); } if (right == null) { throw new ArgumentNullException("right"); } AccountXData lXData = left.XData; if (!lXData.SortCalc) { BindScope boundScope = new BindScope(SortOrder.Context, left); FindSortValues(lXData.SortValues, boundScope); lXData.SortCalc = true; } AccountXData rXData = right.XData; if (!rXData.SortCalc) { BindScope boundScope = new BindScope(SortOrder.Context, right); FindSortValues(rXData.SortValues, boundScope); rXData.SortCalc = true; } return(-SortValueIsLessThan(lXData.SortValues, rXData.SortValues)); // [DM] Invert result because it is used as IComparer output that requires opposite meaning }
public override void Flush() { StringBuilder sb = new StringBuilder(); if (Report.DisplayHandler.Handled) { Logger.Current.Debug("account.display", () => String.Format("Account display predicate: {0}", Report.DisplayHandler.Str())); DispPred.Parse(Report.DisplayHandler.Str()); } MarkAccounts(Report.Session.Journal.Master, Report.FlatHandler.Handled); int displayed = PostedAccounts.Sum(account => PostAccount(account, Report.FlatHandler.Handled)); if (displayed > 1 && !Report.NoTotalHandler.Handled && !Report.PercentHandler.Handled) { BindScope boundScope = new BindScope(Report, Report.Session.Journal.Master); sb.Append(SeparatorFormat?.Calc(boundScope)); if (PrependFormat != null) { sb.AppendFormat(StringExtensions.GetWidthAlignFormatString(PrependWidth), PrependFormat.Calc(boundScope)); } sb.Append(TotalLineFormat.Calc(boundScope)); } Report.OutputStream.Write(sb.ToString()); }
// format_command public static Value FormatCommand(CallScope args) { string arg = CallScope.JoinArgs(args); if (String.IsNullOrEmpty(arg)) { throw new LogicError(LogicError.ErrorMessageUsageFormatText); } Report report = args.FindScope <Report>(); StringBuilder sb = new StringBuilder(); Post post = GetSampleXact(report); sb.AppendLine("--- Input format string ---"); sb.AppendLine(arg); sb.AppendLine(); sb.AppendLine("--- Format elements ---"); Format fmt = new Format(arg); sb.AppendLine(fmt.Dump()); sb.AppendLine("--- Formatted string ---"); BindScope boundScope = new BindScope(args, post); sb.AppendFormat("\"{0}\"", fmt.Calc(boundScope)); sb.AppendLine(); report.OutputStream.Write(sb.ToString()); return(Value.Empty); }
public override void Flush() { StringBuilder sb = new StringBuilder(); Format prependFormat = null; int prependWidth = 0; if (Report.PrependFormatHandler.Handled) { prependFormat = new Format(Report.PrependFormatHandler.Str()); if (Report.PrependWidthHandler.Handled) { prependWidth = Int32.Parse(Report.PrependWidthHandler.Str()); } } foreach (KeyValuePair <Account, int> pair in Accounts.OrderBy(p => p.Key.FullName, StringComparer.Ordinal)) { if (prependFormat != null) { BindScope boundScope = new BindScope(Report, pair.Key); sb.AppendFormat(StringExtensions.GetWidthAlignFormatString(prependWidth), prependFormat.Calc(boundScope)); } if (Report.CountHandler.Handled) { sb.AppendFormat("{0} ", pair.Value); } sb.AppendLine(pair.Key.ToString()); } Report.OutputStream.Write(sb.ToString()); }
public Value AddToValue(Value value, Expr expr = null) { if (HasXData && XData.Compound) { if (!Value.IsNullOrEmpty(XData.CompoundValue)) { value = Value.AddOrSetValue(value, XData.CompoundValue); } } else if (expr != null) { BindScope boundScope = new BindScope(expr.Context, this); Value temp = expr.Calc(boundScope); value = Value.AddOrSetValue(value, temp); } else if (HasXData && XData.Visited && !Value.IsNullOrEmpty(XData.VisitedValue)) { value = Value.AddOrSetValue(value, XData.VisitedValue); } else { value = Value.AddOrSetValue(value, Value.Get(Amount)); } return(value); }
public override void Handle(Post post) { if (!post.HasXData || !post.XData.Displayed) { StringBuilder sb = new StringBuilder(); BindScope boundScope = new BindScope(Report, post); if (!String.IsNullOrEmpty(ReportTitle)) { if (FirstReportTitle) { FirstReportTitle = false; } else { sb.AppendLine(); } ValueScope valScope = new ValueScope(boundScope, Value.StringValue(ReportTitle)); Format groupTitleFormat = new Format(Report.GroupTitleFormatHandler.Str()); sb.Append(groupTitleFormat.Calc(valScope)); ReportTitle = string.Empty; } if (PrependFormat != null) { sb.AppendFormat(StringExtensions.GetWidthAlignFormatString(PrependWidth), PrependFormat.Calc(boundScope)); } if (LastXact != post.Xact) { if (LastXact != null) { BindScope xactScope = new BindScope(Report, LastXact); if (BetweenFormat != null) // DM - in the original code, between_format is called w/o instantiating and returns nothing { sb.Append(BetweenFormat.Calc(xactScope)); } } sb.Append(FirstLineFormat.Calc(boundScope)); LastXact = post.Xact; } else if (LastPost != null && LastPost.GetDate() != post.GetDate()) { sb.Append(FirstLineFormat.Calc(boundScope)); } else { sb.Append(NextLineFormat.Calc(boundScope)); } post.XData.Displayed = true; LastPost = post; Report.OutputStream.Write(sb.ToString()); } }
/// <summary> /// Ported from changed_value_posts::output_revaluation /// </summary> public void OutputRevaluation(Post post, Date date) { if (date.IsValid()) { post.XData.Date = date; } try { BindScope boundScope = new BindScope(Report, post); RepricedTotal = TotalExpr.Calc(boundScope); } finally { post.XData.Date = default(Date); } if (!Value.IsNullOrEmpty(LastTotal)) { Value diff = RepricedTotal - LastTotal; if (!Value.IsNullOrEmptyOrFalse(diff)) { Xact xact = Temps.CreateXact(); xact.Payee = "Commodities revalued"; xact.Date = date.IsValid() ? date : post.ValueDate; if (!ForAccountsReports) { FiltersCommon.HandleValue( /* value= */ diff, /* account= */ RevaluedAccount, /* xact= */ xact, /* temps= */ Temps, /* handler= */ (PostHandler)Handler, /* date= */ xact.Date.Value, /* act_date_p= */ true, /* total= */ RepricedTotal); } else if (ShowUnrealized) { FiltersCommon.HandleValue( /* value= */ diff.Negated(), /* account= */ (diff.IsLessThan(Value.Zero) ? LossesEquityAccount : GainsEquityAccount), /* xact= */ xact, /* temps= */ Temps, /* handler= */ (PostHandler)Handler, /* date= */ xact.Date.Value, /* act_date_p= */ true, /* total= */ new Value(), /* direct_amount= */ false, /* mark_visited= */ true); } } } }
public void BindScope_Description_IsGrandChildDescription() { MockScope mockScope1 = new MockScope(); MockScope mockScope2 = new MockScope("grand-child"); BindScope bindScope = new BindScope(mockScope1, mockScope2); Assert.Equal(mockScope2.Description, bindScope.Description); }
public void ScopeExtensions_SearchScope_MakesReqursiveCallForBindScope() { MockScope parent = new MockScope(); MockScope grandChild = new MockScope(); BindScope bindScope = new BindScope(parent, grandChild); MockScope result = ScopeExtensions.SearchScope <MockScope>(bindScope); Assert.Equal(grandChild, result); }
public override void Handle(Post post) { BindScope boundScope = new BindScope(Context, post); if (Pred.Calc(boundScope).Bool) { post.XData.Matches = true; base.Handle(post); } }
public void BindScope_Contructor_PopulatesGrandChild() { MockScope mockScope1 = new MockScope(); MockScope mockScope2 = new MockScope(); BindScope bindScope = new BindScope(mockScope1, mockScope2); Assert.Equal(mockScope1, bindScope.Parent); Assert.Equal(mockScope2, bindScope.GrandChild); }
public void BindScope_Lookup_CallsGrandChildLookupFirst() { MockScope mockScope1 = new MockScope(); MockScope mockScope2 = new MockScope("grand-child"); BindScope bindScope = new BindScope(mockScope1, mockScope2); ExprOp lookupResult = bindScope.Lookup(SymbolKindEnum.FUNCTION, "dummy"); Assert.Equal(mockScope2.LookupResult, lookupResult); Assert.Equal(1, mockScope2.LookupCalls.Count); }
public IBindingCondition As(BindScope scope) { switch (scope) { default: case Injection.BindScope.Transient: return AsTransient(); case Injection.BindScope.Singleton: return AsSingleton(); } }
public IBindingCondition As(BindScope scope) { switch (scope) { default: case Injection.BindScope.Transient: return(AsTransient()); case Injection.BindScope.Singleton: return(AsSingleton()); } }
public void BindScope_Define_CallsParentAndGrandChildDefine() { MockScope mockScope1 = new MockScope(); MockScope mockScope2 = new MockScope("grand-child"); BindScope bindScope = new BindScope(mockScope1, mockScope2); bindScope.Define(SymbolKindEnum.FUNCTION, "dummy", new ExprOp()); Assert.Equal(1, mockScope1.DefineCalls.Count); Assert.Equal(1, mockScope2.DefineCalls.Count); }
/// <summary> /// Ported from void transfer_details::operator()(post_t& post) /// </summary> public override void Handle(Post post) { Xact xact = Temps.CopyXact(post.Xact); xact.Date = post.GetDate(); Post temp = Temps.CopyPost(post, xact); temp.State = post.State; BindScope boundScope = new BindScope(Scope, temp); Value substitute = Expr.Calc(boundScope); if (!Value.IsNullOrEmpty(substitute)) { switch (WhichElement) { case TransferDetailsElementEnum.SET_DATE: temp.Date = substitute.AsDate; break; case TransferDetailsElementEnum.SET_ACCOUNT: { string accountName = substitute.AsString; if (!String.IsNullOrEmpty(accountName) && !accountName.EndsWith(":")) { Account prevAccount = temp.Account; temp.Account.RemovePost(temp); accountName += ":" + prevAccount.FullName; string[] accountNames = accountName.Split(':'); temp.Account = FiltersCommon.CreateTempAccountFromPath(accountNames, Temps, xact.Journal.Master); temp.Account.AddPost(temp); temp.Account.SetFlags(prevAccount); if (prevAccount.HasXData) { temp.Account.XData.SetFlags(prevAccount.XData); } } break; } case TransferDetailsElementEnum.SET_PAYEE: xact.Payee = substitute.AsString; break; } } base.Handle(temp); }
public void Format_IntegrationTest_AccountLineFormat() { Report report = new Report(new Session()); Account account = new Account(null, "test-account"); string formatStr = "%(ansify_if( justify(scrub(display_total), 20, 20 + int(prepend_width), true, color), bold if should_bold)) %(!options.flat ? depth_spacer : \"\")%-(ansify_if( ansify_if(partial_account(options.flat), blue if color), bold if should_bold))"; Format accountLineFormat = new Format(formatStr); BindScope boundScope = new BindScope(report, account); string result = accountLineFormat.Calc(boundScope); Assert.AreEqual(" 0 test-account", result); }
public void RegisterMetadata(string key, Value value, Item context) { if (CheckingStyle == JournalCheckingStyleEnum.CHECK_WARNING || CheckingStyle == JournalCheckingStyleEnum.CHECK_ERROR) { if (!KnownTags.Contains(key)) { if (context == null) { if (ForceChecking) { FixedMetadata = true; } KnownTags.Add(key); } else if (!FixedMetadata && context != null && context.State != ItemStateEnum.Uncleared) { KnownTags.Add(key); } else if (CheckingStyle == JournalCheckingStyleEnum.CHECK_WARNING) { CurrentContext.Warning(String.Format("Unknown metadata tag '{0}'", key)); } else if (CheckingStyle == JournalCheckingStyleEnum.CHECK_ERROR) { throw new ParseError(String.Format("Unknown metadata tag '{0}'", key)); } } } if (!Value.IsNullOrEmpty(value)) { foreach (CheckExprPair pair in TagCheckExprsMap.GetValues(key)) { BindScope boundScope = new BindScope(CurrentContext.Scope, context); ValueScope valScope = new ValueScope(boundScope, value); if (!pair.Expr.Calc(valScope).AsBoolean) { if (pair.CheckExprKind == CheckExprKindEnum.EXPR_ASSERTION) { throw new ParseError(String.Format(ParseError.ParseError_MetadataAssertionFailedFor, key, value, pair.Expr)); } else { CurrentContext.Warning(String.Format(ParseError.ParseError_MetadataCheckFailedFor, key, value, pair.Expr)); } } } } }
public void BindScope_Lookup_CallsParentLookupNext() { MockScope mockScope1 = new MockScope(); MockScope mockScope2 = new MockScope("grand-child"); mockScope2.LookupResult = null; BindScope bindScope = new BindScope(mockScope1, mockScope2); ExprOp lookupResult = bindScope.Lookup(SymbolKindEnum.FUNCTION, "dummy"); Assert.AreEqual(mockScope1.LookupResult, lookupResult); Assert.AreEqual(1, mockScope1.LookupCalls.Count); Assert.AreEqual(1, mockScope2.LookupCalls.Count); }
private static Value FnAll(CallScope args) { Account account = args.Context <Account>(); ExprOp expr = args.Get <ExprOp>(0); foreach (Post p in account.Posts) { BindScope boundScope = new BindScope(args, p); if (!expr.Calc(boundScope, args.Locus, args.Depth).AsBoolean) { return(Value.False); } } return(Value.True); }
private static Value FnAny(CallScope args) { Post post = args.Context <Post>(); ExprOp expr = args.Get <ExprOp>(0); foreach (Post p in post.Xact.Posts) { BindScope boundScope = new BindScope(args, p); if (expr.Calc(boundScope, args.Locus, args.Depth).AsBoolean) { return(Value.True); } } return(Value.False); }
public virtual int PostAccount(Account account, bool flat) { if (!flat && account.Parent != null) { PostAccount(account.Parent, flat); } if (account.XData.ToDisplay && !account.XData.Displayed) { StringBuilder sb = new StringBuilder(); Logger.Current.Debug("account.display", () => String.Format("Displaying account: {0}", account.FullName)); account.XData.Displayed = true; BindScope boundScope = new BindScope(Report, account); if (!String.IsNullOrEmpty(ReportTitle)) { if (FirstReportTitle) { FirstReportTitle = false; } else { sb.AppendLine(); } ValueScope valScope = new ValueScope(boundScope, Value.StringValue(ReportTitle)); Format groupTitleFormat = new Format(Report.GroupTitleFormatHandler.Str()); sb.Append(groupTitleFormat.Calc(valScope)); ReportTitle = string.Empty; } if (PrependFormat != null) { sb.AppendFormat(StringExtensions.GetWidthAlignFormatString(PrependWidth), PrependFormat.Calc(boundScope)); } sb.Append(AccountLineFormat.Calc(boundScope)); Report.OutputStream.Write(sb.ToString()); return(1); } return(0); }
public Amount ResolveExpr(Scope scope, Expr expr) { BindScope boundScope = new BindScope(scope, this); Value result = expr.Calc(boundScope); if (result.Type == ValueTypeEnum.Integer) { return(result.AsAmount); } else { if (result.Type != ValueTypeEnum.Amount) { throw new AmountError(AmountError.ErrorMessageAmountExpressionsMustResultInASimpleAmount); } return(result.AsAmount); } }
private Value CallLambda(ExprOp func, Scope scope, CallScope callArgs, ExprOp locus, int depth) { int argsIndex = 0; long argsCount = callArgs.Size; SymbolScope argsScope = new SymbolScope(Scope.EmptyScope); for (ExprOp sym = func.Left; sym != null; sym = sym.HasRight ? sym.Right : null) { ExprOp varName = sym.Kind == OpKindEnum.O_CONS ? sym.Left : sym; if (!varName.IsIdent) { throw new CalcError(CalcError.ErrorMessageInvalidFunctionDefinition); } if (argsIndex == argsCount) { Logger.Current.Debug("expr.calc", () => String.Format("Defining function argument as null: {0}", varName.AsIdent)); argsScope.Define(SymbolKindEnum.FUNCTION, varName.AsIdent, WrapValue(Value.Empty)); } else { Logger.Current.Debug("expr.calc", () => String.Format("Defining function argument from call_args: {0}", varName.AsIdent)); argsScope.Define(SymbolKindEnum.FUNCTION, varName.AsIdent, WrapValue(callArgs[argsIndex++])); } } if (argsIndex < argsCount) { throw new CalcError(String.Format(CalcError.ErrorMessageTooFewArgumentsInFunctionCall, argsCount, argsIndex)); } if (func.Right.IsScope) { BindScope outerScope = new BindScope(scope, func.Right.AsScope); BindScope boundScope = new BindScope(outerScope, argsScope); return(func.Right.Left.Calc(boundScope, locus, depth + 1)); } else { return(func.Right.Calc(argsScope, locus, depth + 1)); } }
public Tuple <int, int> MarkAccounts(Account account, bool flat) { int visited = 0; int toDisplay = 0; foreach (Account acc in account.Accounts.Values) { Tuple <int, int> i = MarkAccounts(acc, flat); visited += i.Item1; toDisplay += i.Item2; } if (Logger.Current.ShowDebug(DebugAccountDisplay)) { Logger.Current.Debug(DebugAccountDisplay, () => "Considering account: " + account.FullName); if (account.HasXFlags(d => d.Visited)) { Logger.Current.Debug(DebugAccountDisplay, () => " it was visited itself"); } Logger.Current.Debug(DebugAccountDisplay, () => " it has " + visited + " visited children"); Logger.Current.Debug(DebugAccountDisplay, () => " it has " + toDisplay + " children to display"); } if (account.Parent != null && (account.HasXFlags(d => d.Visited) || (!flat && visited > 0))) { BindScope boundScope = new BindScope(Report, account); CallScope callScope = new CallScope(boundScope); if ((!flat && toDisplay > 1) || ((flat || toDisplay != 1 || account.HasXFlags(d => d.Visited)) && (Report.EmptyHandler.Handled || !Value.IsNullOrEmptyOrFalse(Report.DisplayValue(Report.FnDisplayTotal(callScope)))) && !Value.IsNullOrEmptyOrFalse(DispPred.Calc(boundScope)))) { account.XData.ToDisplay = true; Logger.Current.Debug(DebugAccountDisplay, () => "Marking account as TO_DISPLAY"); toDisplay = 1; } visited = 1; } return(new Tuple <int, int>(visited, toDisplay)); }
public override void Handle(Post post) { BindScope boundScope = new BindScope(Report, post); Value result = GroupByExpr.Calc(boundScope); if (!Value.IsNullOrEmpty(result)) { IList <Post> posts; if (PostsMap.TryGetValue(result, out posts)) { posts.Add(post); } else { PostsMap.Add(result, new List <Post>() { post }); } } }
private static Value FnAll(CallScope args) { Post post = args.Context <Post>(); ExprOp expr = args.Get <ExprOp>(0); foreach (Post p in post.Xact.Posts) { BindScope boundScope = new BindScope(args, p); if (p == post && args.Has <ExprOp>(1) && !args.Get <ExprOp>(1).Calc(boundScope, args.Locus, args.Depth).AsBoolean) { // If the user specifies any(EXPR, false), and the context is a // posting, then that posting isn't considered by the test. ; // skip it } else if (expr.Calc(boundScope, args.Locus, args.Depth).AsBoolean) { return(Value.False); } } return(Value.True); }
// parse_command public static Value ParseCommand(CallScope args) { string arg = CallScope.JoinArgs(args); if (String.IsNullOrEmpty(arg)) { throw new LogicError(LogicError.ErrorMessageUsageParseText); } Report report = args.FindScope <Report>(); StringBuilder sb = new StringBuilder(); Post post = GetSampleXact(report); sb.AppendLine("--- Input expression ---"); sb.AppendLine(arg); sb.AppendLine("--- Text as parsed ---"); Expr expr = new Expr(arg); sb.AppendLine(expr.Print()); sb.AppendLine("--- Expression tree ---"); sb.Append(expr.Dump()); BindScope boundScope = new BindScope(args, post); expr.Compile(boundScope); sb.AppendLine("--- Compiled tree ---"); sb.Append(expr.Dump()); sb.AppendLine("--- Calculated value ---"); Value result = expr.Calc(); sb.AppendLine(result.StripAnnotations(report.WhatToKeep()).Dump()); report.OutputStream.Write(sb.ToString()); return(Value.Empty); }
private MainApplicationContext InitializeSession(IEnumerable <string> args, CancellationToken token) { using (var memoryStreamManager = new MemoryStreamManager(InputText)) { var context = ServiceEngine.CreateContext(memoryStreamManager); token.Register(() => context.CancellationSignal = CaughtSignalEnum.INTERRUPTED); using (context.AcquireCurrentThread()) { GlobalScope.HandleDebugOptions(args); Logger.Current.Info(() => LedgerSessionStarting); GlobalScope = new GlobalScope(context.EnvironmentVariables); GlobalScope.Session.FlushOnNextDataFile = true; try { // Look for options and a command verb in the command-line arguments BindScope boundScope = new BindScope(GlobalScope, GlobalScope.Report); args = GlobalScope.ReadCommandArguments(boundScope, args); GlobalScope.Session.ReadJournalFiles(); Status = 0; } catch (CountError errors) { Status = errors.Count; } catch (Exception err) { GlobalScope.ReportError(err); } OutputText = memoryStreamManager.GetOutputText(); ErrorText = memoryStreamManager.GetErrorText(); return(context); } } }
/// <summary> /// Ported from void changed_value_posts::operator()(post_t& post) /// </summary> public override void Handle(Post post) { if (LastPost != null) { if (!ForAccountsReports && !HistoricalPricesOnly) { OutputIntermediatePrices(LastPost, post.ValueDate); } OutputRevaluation(LastPost, post.ValueDate); } if (ChangedValuesOnly) { post.XData.Displayed = true; } base.Handle(post); BindScope boundScope = new BindScope(Report, post); LastTotal = TotalExpr.Calc(boundScope); LastPost = post; }
protected BindAttributeBase(BindScope bindingScope) { BindingScope = bindingScope; }
public BindFactoryAttribute(Type contractType, BindScope scope) : this(contractType, Type.EmptyTypes, scope) { }
public BindAttribute(Type contractType, Type[] baseTypes, BindScope bindingScope, ConditionSource conditionSource, ConditionComparer conditionComparer, object conditionTarget) : base(bindingScope, conditionSource, conditionComparer, conditionTarget) { ContractType = contractType; BaseTypes = baseTypes; }
public BindAttribute(Type contractType, BindScope bindingScope, ConditionSource conditionSource, ConditionComparer conditionComparer, object conditionTarget) : this(contractType, Type.EmptyTypes, bindingScope, conditionSource, conditionComparer, conditionTarget) { }
public BindAttribute(Type contractType, Type[] baseTypes, BindScope bindingScope) : base(bindingScope) { ContractType = contractType; BaseTypes = baseTypes; }
public BindFactoryAttribute(Type contractType, Type[] baseTypes, BindScope scope) : base(scope) { ContractType = contractType; BaseTypes = baseTypes; }
public BindAttribute(Type contractType, BindScope bindingScope) : this(contractType, Type.EmptyTypes, bindingScope) { }
public BindAllAttribute(BindScope bindingScope) : base(bindingScope) { }
public BindAllAttribute(BindScope bindingScope, ConditionSource conditionSource, ConditionComparer conditionComparer, object conditionTarget) : base(bindingScope, conditionSource, conditionComparer, conditionTarget) { }