public ProductionInfoManager(IProduction root) { CodeContract.RequiresArgumentNotNull(root, "root"); var aggregator = new ProductionAggregationVisitor(); var productions = root.Accept(aggregator, new List<IProduction>()); m_productions = productions.ToArray(); RootProduction = root; var ffVisitor = new FirstFollowVisitor(); bool isChanged; do { isChanged = false; foreach (var p in productions) { isChanged = p.Accept(ffVisitor, isChanged); } } while (isChanged); }
public Grammar(INonTerminal start, IProduction[] productions, ILexerRule[] lexerRules, ILexerRule[] ignore) { Assert.IsNotNullOrEmpty(productions, "productions"); Assert.IsNotNull(start, "start"); _productionIndex = CreateProductionIndex(productions); _lexerRuleIndex = CreateLexerRuleIndex(lexerRules); Productions = new ReadOnlyList<IProduction>(productions ?? EmptyProductionArray); LexerRules = new ReadOnlyList<ILexerRule>(lexerRules ?? EmptyLexerRuleArray); Ignores = new ReadOnlyList<ILexerRule>(ignore ?? EmptyLexerRuleArray); Start = start; }
public State(IProduction production, int position, int origin) { Assert.IsNotNull(production, "production"); Assert.IsGreaterThanEqualToZero(position, "position"); Assert.IsGreaterThanEqualToZero(origin, "origin"); Production = production; Origin = origin; Length = position; PostDotSymbol = GetPostDotSymbol(position, production); PreDotSymbol = GetPreDotSymbol(position, production); }
protected StateBase(IProduction production, int position, int origin) { Assert.IsNotNull(production, nameof(production)); Assert.IsGreaterThanEqualToZero(position, nameof(position)); Assert.IsGreaterThanEqualToZero(origin, nameof(origin)); Production = production; Origin = origin; Position = position; PostDotSymbol = GetPostDotSymbol(position, production); PreDotSymbol = GetPreDotSymbol(position, production); }
private void PredictProduction(INormalState evidence, int j, IProduction production) { // TODO: Pre-Compute Leo Items. If item is 1 step from being complete, add a transition item var predictedState = new NormalState(production, 0, j); if (_chart.Enqueue(j, predictedState)) Log("Predict", j, predictedState); var isNullable = Grammar.IsNullable(evidence.PostDotSymbol as INonTerminal); if (isNullable) { var nullParseNode = CreateNullParseNode(evidence.PostDotSymbol, j); var aycockHorspoolState = evidence.NextState(); var evidenceParseNode = evidence.ParseNode as IInternalForestNode; if (evidenceParseNode == null) aycockHorspoolState.ParseNode = CreateParseNode(aycockHorspoolState, null, nullParseNode, j); else if (evidenceParseNode.Children.Count > 0 && evidenceParseNode.Children[0].Children.Count > 0) { var firstChildNode = evidenceParseNode; var parseNode = CreateParseNode(aycockHorspoolState, firstChildNode, nullParseNode, j); aycockHorspoolState.ParseNode = parseNode; } if (_chart.Enqueue(j, aycockHorspoolState)) Log("Predict", j, aycockHorspoolState); } }
public ProductionInfo GetInfo(IProduction production) { return (production as ProductionBase).Info; }
private static ISymbol GetPreDotSymbol(int position, IProduction production) { if (position == 0 || production.IsEmpty) return null; return production.RightHandSide[position - 1]; }
public NormalState(IProduction production, int position, int origin) : base(production, position, origin) { _hashCode = ComputeHashCode(); }
public void UpdateUI(StaticInstance selectedFacility) { production = selectedFacility.myFacilities[0] as IProduction; UpdateUI(); }
public IList <Item> GetLiveItemsWaitingForProduction(IProduction production) => Items .Where(i => i.IsWaitingFor(production)) .ToList();
public void Input(Lexeme z) { while (true) { var heads = m_heads; for (int i = 0; i < heads.Count; i++) { var head = heads[i]; int stateNumber = head.TopStackStateIndex; bool isShiftedOrReduced = false; var shiftLexer = m_transitions.GetLexersInShifting(stateNumber); int tokenIndex; if (shiftLexer == null) { tokenIndex = z.TokenIndex; } else { tokenIndex = z.GetTokenIndex(shiftLexer.Value); } //get shift var shifts = m_transitions.GetShift(stateNumber, tokenIndex); //shifts var shift = shifts; while (shift != null) { isShiftedOrReduced = true; var newHead = head.Clone(); newHead.Shift(z, shift.Value); //save shifted heads m_shiftedHeads.Add(newHead); //get next shift shift = shift.GetNext(); } //reduces var reduceLexer = m_transitions.GetLexersInReducing(stateNumber); if (reduceLexer == null) { tokenIndex = z.TokenIndex; } else { tokenIndex = z.GetTokenIndex(reduceLexer.Value); } var reduces = m_transitions.GetReduce(stateNumber, tokenIndex); var reduce = reduces; while (reduce != null) { isShiftedOrReduced = true; int productionIndex = reduce.Value; IProduction production = m_transitions.NonTerminals[productionIndex]; var reducedHead = head.Clone(); reducedHead.Reduce(production, m_reducer, z); if (reducedHead.IsAccepted) { m_acceptedHeads.Add(reducedHead); } else { //add back to queue, until shifted m_reducedHeads.Add(reducedHead); } //get next reduce reduce = reduce.GetNext(); } if (!isShiftedOrReduced) { m_errorCandidates.Add(head); } } if (m_reducedHeads.Count > 0) { m_heads.Clear(); m_cleaner.CleanHeads(m_reducedHeads, m_heads); m_reducedHeads.Clear(); continue; } else if (m_shiftedHeads.Count == 0 && m_acceptedHeads.Count == 0) { //no action for current lexeme, error recovery RecoverError(z); } else { break; } } CleanShiftedAndAcceptedHeads(); }
private void ReduceAndShiftForRecovery(Lexeme z, ParserHead head, IList <ParserHead> shiftTarget, int syntaxError) { Queue <ParserHead> recoverQueue = new Queue <ParserHead>(); for (int j = 0; j < m_transitions.TokenCount - 1; j++) { recoverQueue.Enqueue(head); while (recoverQueue.Count > 0) { var recoverHead = recoverQueue.Dequeue(); int recoverStateNumber = recoverHead.TopStackStateIndex; var shiftLexer = m_transitions.GetLexersInShifting(recoverStateNumber); int tokenIndex; if (shiftLexer == null) { tokenIndex = z.TokenIndex; } else { tokenIndex = z.GetTokenIndex(shiftLexer.Value); } var recoverShifts = m_transitions.GetShift(recoverStateNumber, j); var recoverShift = recoverShifts; while (recoverShift != null) { var insertHead = recoverHead.Clone(); var insertLexeme = z.GetErrorCorrectionLexeme(j, m_transitions.GetTokenDescription(j)); insertHead.Shift(insertLexeme, recoverShift.Value); insertHead.IncreaseErrorRecoverLevel(); insertHead.AddError(new ErrorRecord(syntaxError, z.Value.Span) { ErrorArgument = insertLexeme.Value }); shiftTarget.Add(insertHead); recoverShift = recoverShift.GetNext(); } var reduceLexer = m_transitions.GetLexersInReducing(recoverStateNumber); if (reduceLexer == null) { tokenIndex = z.TokenIndex; } else { tokenIndex = z.GetTokenIndex(reduceLexer.Value); } var recoverReduces = m_transitions.GetReduce(recoverStateNumber, j); var recoverReduce = recoverReduces; while (recoverReduce != null) { int productionIndex = recoverReduce.Value; IProduction production = m_transitions.NonTerminals[productionIndex]; var reducedHead = recoverHead.Clone(); reducedHead.Reduce(production, m_reducer, z); //add back to queue, until shifted m_recoverReducedHeads.Add(reducedHead); //get next reduce recoverReduce = recoverReduce.GetNext(); } if (m_recoverReducedHeads.Count > 0) { m_tempHeads.Clear(); m_cleaner.CleanHeads(m_recoverReducedHeads, m_tempHeads); m_recoverReducedHeads.Clear(); foreach (var recoveredHead in m_tempHeads) { recoverQueue.Enqueue(recoveredHead); } } } } }
private void RecoverError(Lexeme z) { List <ParserHead> shiftedHeads = m_shiftedHeads; m_heads.Clear(); int errorHeadCount = m_errorCandidates.Count; Debug.Assert(errorHeadCount > 0); if (errorHeadCount > c_panicRecoveryThreshold) { //Panic recovery //to the 1st head: //pop stack until there's a state S, which has a Goto action of a non-terminal A //discard input until there's an token a in Follow(A) //push Goto(s, A) into stack //discard all other heads m_heads.Clear(); m_heads.AddRange(shiftedHeads.Where(h => h.ErrorRecoverLevel == 0)); shiftedHeads.Clear(); ParserHead errorHead1 = m_errorCandidates[0]; m_errorCandidates.Clear(); IProduction p = errorHead1.PanicRecover(m_transitions, z.Value.Span); var follow = (p as ProductionBase).Info.Follow; m_heads.Add(errorHead1); throw new PanicRecoverException(follow); } for (int i = 0; i < errorHeadCount; i++) { var head = m_errorCandidates[i]; if (!z.IsEndOfStream) { //option 1: remove //remove current token and continue var deleteHead = head.Clone(); deleteHead.IncreaseErrorRecoverLevel(); deleteHead.AddError(new ErrorRecord(m_errorDef.TokenUnexpectedId, z.Value.Span) { ErrorArgument = z.Value }); shiftedHeads.Add(deleteHead); //option 2: replace //replace the current input char with all possible shifts token and continue ReduceAndShiftForRecovery(z, head, shiftedHeads, m_errorDef.TokenMistakeId); } //option 3: insert //insert all possible shifts token and continue ReduceAndShiftForRecovery(z, head, m_heads, m_errorDef.TokenMissingId); } }
public ImprovementBuilt(City city, IWonder wonder) { _city = city; _improvement = wonder; }
public ImprovementBuilt(City city, IBuilding building) { _city = city; _improvement = building; }
public void Reduce(IProduction production, ReduceVisitor reducer, Lexeme lookahead) { #if HISTORY var from = m_topStack.StateIndex; #endif if (production == null) { //Accept Debug.Assert(m_topStack.PrevNode.StateIndex == 0); //TODO: accepted IsAccepted = true; return; } if (production.AggregatesAmbiguities) { AmbiguityAggregator = ((ProductionBase)production).CreateAggregator(); } var reduceResult = production.Accept(reducer, m_topStack); m_topStack = reduceResult.NewTopStack; var reduceError = reduceResult.ReduceError; if (reduceError != null) { IncreaseErrorRecoverLevel(); if (reduceError.ErrorPosition == null) { reduceError = new ErrorRecord(reduceError.ErrorId, lookahead.Value.Span); } AddError(reduceError); } #if HISTORY var to = m_topStack.StateIndex; History.Add(String.Format("R{0}:{1}", from, to)); #endif }
private void AddProductionToIndex(IProduction production) { var leftHandSide = production.LeftHandSide; if (!_productionIndex.ContainsKey(leftHandSide)) { _productionIndex.Add(leftHandSide, new ReadWriteList<IProduction>()); } _productionIndex[leftHandSide].Add(production); }
public void AddToProduction(IProduction production) { _onGoingProductions.Add(production); }
internal bool AddEdge(IProduction symbol, LR0State targetState) { ProductionBase production = symbol as ProductionBase; return(m_edges.Add(new LR0Edge(Index, production.Info.Index, targetState.Index))); }
public void RemoveFromProduction(IProduction production) { _onGoingProductions.Remove(production); }
public State(IProduction production, int position, int origin, INode parseNode) : this(production, position, origin) { ParseNode = parseNode; }
public void Reduce(IProduction production, ReduceVisitor reducer, Lexeme lookahead) { #if HISTORY var from = m_topStack.StateIndex; #endif if (production == null) { //Accept Debug.Assert(m_topStack.PrevNode.StateIndex == 0); //TODO: accepted IsAccepted = true; return; } if (Priority < production.Priority) Priority = production.Priority; var reduceResult = production.Accept(reducer, m_topStack); m_topStack = reduceResult.NewTopStack; var reduceError = reduceResult.ReduceError; if (reduceError != null) { IncreaseErrorRecoverLevel(); if (reduceError.ErrorPosition == null) { reduceError.ErrorPosition = lookahead.Span; } AddError(reduceError); } #if HISTORY var to = m_topStack.StateIndex; History.Add(String.Format("R{0}:{1}", from, to)); #endif }
private static ISymbol GetPostDotSymbol(int position, IProduction production) { if (position >= production.RightHandSide.Count) return null; return production.RightHandSide[position]; }
private DottedRule GetPreComputedState(IProduction production, int position) { return(_states[production][position]); }
private ISet<LR0Item> GetGoto(IEnumerable<LR0Item> state, IProduction symbol) { ISet<LR0Item> resultSet = new HashSet<LR0Item>(); var symbolIndex = m_infoManager.GetInfo(symbol).Index; foreach (var item in state) { var production = m_infoManager.Productions[item.ProductionIndex]; var info = m_infoManager.GetInfo(production); var dotSymbols = production.Accept(m_dotSymbolVisitor, item.DotLocation); if (dotSymbols.Count == 1 && m_infoManager.GetInfo(dotSymbols[0]).Index == symbolIndex) { resultSet.Add(new LR0Item(info.Index, item.DotLocation + 1)); } else if (dotSymbols.Count == 2) { if (m_infoManager.GetInfo(dotSymbols[0]).Index == symbolIndex || m_infoManager.GetInfo(dotSymbols[1]).Index == symbolIndex) { resultSet.Add(new LR0Item(info.Index, item.DotLocation + 1)); } } } return GetClosure(resultSet); }
public CityView(City city, bool founded = false, bool firstView = false, IProduction production = null, bool captured = false, bool disorder = false, bool weLovePresidentDay = false) { _dialogText = TextSettings.ShadowText(15, 5); _dialogText.FontId = 5; _city = city; _production = production; _background = new Picture(Resources["HILL"]); _founded = founded; _firstView = firstView; Palette = _background.Palette; _overlay = new Picture(_background); if (founded) { return; } DrawBuildings(); this.AddLayer(_background); if (_captured = captured) { Picture invaders; int xx = 0, yy = 2, ww = 78, hh = 60; if (Game.CurrentPlayer.HasAdvance <Conscription>()) { invaders = Resources["INVADERS"]; } else if (Game.CurrentPlayer.HasAdvance <Gunpowder>()) { invaders = Resources["INVADER2"]; } else { invaders = Resources["INVADER3"]; xx = 1; yy = 1; ww = 78; hh = 65; _y = 133; } _invadersOrRevolters = new Picture[10]; for (int ii = 0; ii < 10; ii++) { int frameX = (ii % 4); int frameY = (ii - frameX) / 4; _invadersOrRevolters[ii] = invaders[xx + (frameX * (ww + 1)), yy + (frameY * (hh + 1)), ww, hh]; } _x = 0; int totalLuxuries = Game.GetPlayer(_city.Owner).Cities.Sum(x => x.Luxuries); int totalGold = Game.GetPlayer(_city.Owner).Gold; int cityLuxuries = _city.Luxuries; if (cityLuxuries == 0) { cityLuxuries = 1; } int captureGold = (int)Math.Floor(((float)totalGold / totalLuxuries) * cityLuxuries); if (captureGold < 0) { captureGold = 0; } Game.GetPlayer(_city.Owner).Gold -= (short)captureGold; Game.CurrentPlayer.Gold += (short)captureGold; string[] lines = new [] { $"{Game.CurrentPlayer.TribeNamePlural} capture", $"{city.Name}. {captureGold} gold", "pieces plundered." }; int width = lines.Max(l => Resources.GetTextSize(5, l).Width) + 12; Picture dialog = new Picture(width, 54) .Tile(Pattern.PanelGrey, 1, 1) .DrawRectangle() .DrawRectangle3D(1, 1, width - 2, 52) .DrawText(lines[0], 5, 6, _dialogText) .DrawText(lines[1], 5, 21, _dialogText) .DrawText(lines[2], 5, 36, _dialogText) .As <Picture>(); _background.AddLayer(dialog, 80, 8); } if (_disorder = disorder) { Picture revolters; int xx = 1, yy = 1, ww, hh; if (Game.CurrentPlayer.HasAdvance <Conscription>()) { ww = 78; hh = 63; revolters = Resources["RIOT"]; } else { ww = 74; hh = 65; revolters = Resources["RIOT2"]; } _invadersOrRevolters = new Picture[10]; for (int ii = 0; ii < 10; ii++) { int frameX = (ii % 4); int frameY = (ii - frameX) / 4; _invadersOrRevolters[ii] = revolters[xx + (frameX * (ww + 1)), yy + (frameY * (hh + 1)), ww, hh]; } _x = 0; string[] lines = new [] { $"Civil disorder in", $"{city.Name}! Mayor", "flees in panic." }; int width = lines.Max(l => Resources.GetTextSize(5, l).Width) + 12; Picture dialog = new Picture(width, 54) .Tile(Pattern.PanelGrey, 1, 1) .DrawRectangle() .DrawRectangle3D(1, 1, width - 2, 52) .DrawText(lines[0], 5, 6, _dialogText) .DrawText(lines[1], 5, 21, _dialogText) .DrawText(lines[2], 5, 36, _dialogText) .As <Picture>(); _background.AddLayer(dialog, 80, 8); } if (_weLovePresidentDay = weLovePresidentDay) { Picture marchers; int xx = 1, yy = 1, ww = 78, hh = 65; if (Game.CurrentPlayer.HasAdvance <Conscription>()) { marchers = Resources["LOVE2"]; } else { marchers = Resources["LOVE1"]; } _invadersOrRevolters = new Picture[10]; for (int ii = 0; ii < 10; ii++) { int frameX = (ii % 4); int frameY = (ii - frameX) / 4; _invadersOrRevolters[ii] = marchers[xx + (frameX * (ww + 1)), yy + (frameY * (hh + 1)), ww, hh]; var g = new Graphics.ImageFormats.GifFile(_invadersOrRevolters[ii]); System.IO.File.WriteAllBytes($@"c:\temp\{ii}.gif", g.GetBytes()); } _x = 240; string[] lines = new [] { $"'We Love the President'", $"day celebrated in", $"{city.Name}!" }; int width = lines.Max(l => Resources.GetTextSize(5, l).Width) + 12; Picture dialog = new Picture(width, 54) .Tile(Pattern.PanelGrey, 1, 1) .DrawRectangle() .DrawRectangle3D(1, 1, width - 2, 52) .DrawText(lines[0], 5, 6, _dialogText) .DrawText(lines[1], 5, 21, _dialogText) .DrawText(lines[2], 5, 36, _dialogText) .As <Picture>(); _background.AddLayer(dialog, 80, 8); } if (production != null) { _noiseMap = new byte[320, 200]; for (int x = 0; x < 320; x++) { for (int y = 0; y < 200; y++) { _noiseMap[x, y] = (byte)Common.Random.Next(1, NOISE_COUNT); } } string[] lines = new [] { $"{_city.Name} builds", $"{(production as ICivilopedia).Name}." }; int width = lines.Max(l => Resources.GetTextSize(5, l).Width) + 12; Picture dialog = new Picture(width, 39) .Tile(Pattern.PanelGrey, 1, 1) .DrawRectangle() .DrawRectangle3D(1, 1, width - 2, 37) .DrawText(lines[0], 5, 6, _dialogText) .DrawText(lines[1], 5, 21, _dialogText) .As <Picture>(); foreach (Picture picture in new[] { _background, _overlay }) { picture.AddLayer(dialog, 80, 10); } return; } if (captured) { return; } this.DrawText(_city.Name, 5, 5, 161, 3, TextAlign.Center) .DrawText(_city.Name, 5, 15, 160, 2, TextAlign.Center) .DrawText(Game.GameYear, 5, 5, 161, 16, TextAlign.Center) .DrawText(Game.GameYear, 5, 15, 160, 15, TextAlign.Center); if (firstView) { _fadeStep = 0.0f; FadeColours(); return; } int i = 0; int group = -1; int offsetX = 24; bool modern = Human.HasAdvance <Industrialization>(); foreach (Citizen citizen in _city.Citizens) { if (group != (group = Common.CitizenGroup(citizen)) && group > 0) { offsetX += 8; } int sx = ((int)(citizen) * 35) + 1, sy = (modern ? 1 : 52); int sw = 34, sh = (modern ? 50 : 52); int dx = (int)(citizen) + offsetX + (11 * i++), dy = 140; this.AddLayer(Resources["POP"][sx, sy, sw, sh], dx, dy); } }
// create a new instance from the injected classes public ProductionController(yamamadbContext db, IProduction production) { _db = db; _production = production; }
public FactorCalculator(IProduction production) { this.production = production; }
private void PredictProduction(IState evidence, int j, IProduction production) { // TODO: Pre-Compute Leo Items. If item is 1 step from being complete, add a transition item var predictedState = new State(production, 0, j); if (_chart.Enqueue(j, predictedState)) Log("Predict", j, predictedState); var stateIsNullable = predictedState.Production.IsEmpty; if (stateIsNullable) { var aycockHorspoolState = evidence.NextState(j); var predictedParseNode = CreateNullParseNode( predictedState.Production.LeftHandSide, j); aycockHorspoolState.ParseNode = CreateParseNode( aycockHorspoolState, evidence.ParseNode, predictedParseNode, j); if (_chart.Enqueue(j, aycockHorspoolState)) Log("Predict", j, aycockHorspoolState); } }
internal bool AddEdge(IProduction symbol, LR0State targetState) { ProductionBase production = symbol as ProductionBase; return m_edges.Add(new LR0Edge(Index, production.Info.Index, targetState.Index)); }
/// <summary> /// Creates a token from <paramref name="production"/> /// </summary> /// <param name="production"> /// production to wrap. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="production"/> is a null reference (Nothing in /// Visual Basic). /// </exception> public ProductionToken(IProduction production) { if (production==null) throw new ArgumentNullException("production"); this.production=production; }
internal void AddReduce(IProduction reduceSymbol, IProduction reduceProduction) { m_reduces.Add(new ReduceAction(reduceSymbol, reduceProduction)); }
private void AddProduction(IProduction production) { _productions.Add(production); AddProductionToIndex(production); AddProductionToReverseLookup(production); }
/// <summary> /// /// </summary> /// <param name="production"></param> public ProductionException(IProduction production) { this.production = production; }
private void AddProductionToReverseLookup(IProduction production) { // get nullable nonterminals: http://cstheory.stackexchange.com/a/2493/32787 if (production.IsEmpty) _nullable.Add(production.LeftHandSide); for(var s = 0; s< production.RightHandSide.Count; s++) { var symbol = production.RightHandSide[s]; if (symbol.SymbolType != SymbolType.NonTerminal) continue; var nonTerminal = symbol as INonTerminal; UniqueList<IProduction> hashSet = null; if (!_reverseLookup.TryGetValue(nonTerminal, out hashSet)) { hashSet = new UniqueList<IProduction>(); _reverseLookup.Add(nonTerminal, hashSet); } hashSet.Add(production); } }
internal ReduceAction(IProduction reduceTerminl, IProduction reduceProduction) { this.m_reduceTerminal = reduceTerminl; this.m_reduceProduction = reduceProduction; }
public SingularRule(string name, IProduction prod) { this.name = name; this.p = prod; }