Ejemplo n.º 1
0
 public override PathCond And(CachedAtom cond)
 {
     if (conds.Contains(cond.Negate()))
     {
         return(FALSE);
     }
     else
     {
         return(Make(AddItem(this.conds, cond)));
     }
 }
        public void AddBody(SoftBody body)
        {
            if (body == null)
            {
                throw new ArgumentNullException("body", "body can't be null.");
            }
            if (softbodies.Contains(body))
            {
                throw new ArgumentException("The body was already added to the world.", "body");
            }

            this.softbodies.Add(body);
            this.CollisionSystem.AddEntity(body);

            events.RaiseAddedSoftBody(body);

            foreach (Constraint constraint in body.EdgeSprings)
            {
                AddConstraint(constraint);
            }

            foreach (SoftBody.MassPoint massPoint in body.VertexBodies)
            {
                events.RaiseAddedRigidBody(massPoint);
                rigidBodies.Add(massPoint);
            }
        }
Ejemplo n.º 3
0
        public void AddBody(SoftBody body)
        {
            if (body == null)
            {
                throw new ArgumentNullException("body", "body can't be null.");
            }
            if (softbodies.Contains(body))
            {
                throw new ArgumentException("The body was already added to the world.", "body");
            }

            this.softbodies.Add(body);
            this.CollisionSystem.AddEntity(body);

            events.RaiseAddedSoftBody(body);

            foreach (Constraint constraint in body.EdgeSprings)
            {
                CBFrame.Utils.Logger.Debug("line260 body2.linearVelocity:" + constraint.body2.linearVelocity + ",body1.linearVelocity:" + constraint.body1.linearVelocity);
                AddConstraint(constraint);
            }

            foreach (SoftBody.MassPoint massPoint in body.VertexBodies)
            {
                events.RaiseAddedRigidBody(massPoint);
                rigidBodies.Add(massPoint);
            }
        }
        public static string NextUniqueString(this Random random, HashList <string> hash, int size, bool includeDigits = false)
        {
            char[] chars         = new char[size];
            char[] charSet       = includeDigits ? StringGenerator.AsciiLetterOrDigit : StringGenerator.AsciiLetter;
            int    charSetLength = charSet.Length;
            int    count         = 0;
            string s;

            do
            {
                if (count > 20)
                {
                    count = 0;
                    size++;
                    chars = new char[size];
                }

                for (int i = 0; i < size; i++)
                {
                    chars[i] = charSet[random.Next(0, charSetLength)];
                }

                s = new string(chars);
                count++;
            }while (hash.Contains(s));

            return(s);
        }
Ejemplo n.º 5
0
        void AddAlert(TDBaseAlertData alert)
        {
            if (AlertDatasSet.Contains(alert))
            {
                return;
            }
            GameObject    go        = GOPool.Spawn();
            BaseAlertItem alertItem = go.GetComponent <BaseAlertItem>();

            alertItem.PUIView = this;
            alertItem.CancleInit();
            alertItem.Init(new UButtonData
            {
                Icon         = () => alert.GetIcon(),
                Bg           = () => alert.GetBg(),
                OnClick      = (x, y) => alert.DoClick(x, y),
                OnEnter      = (x) => alert.DoEnter(),
                OnShowActive = OnAlertShow,
            });
            alertItem.SetID(alert.ID);
            alertItem.Show(true, true);
            alertItem.RectTrans.position = StartPos.position;
            ActiveItems.Add(alertItem);
            AlertDatasSet.Add(alert);
        }
Ejemplo n.º 6
0
 public void Add(int id)
 {
     if (_list.Contains(id))
     {
         return;
     }
     _list.Add(id);
 }
Ejemplo n.º 7
0
 public override PathCond Or(PathCond other)
 {
     if (other is CachedAtom && conds.Contains(((CachedAtom)other).Negate()))
     {
         // Reduce Or(OR(...,e,...), NOT(e)) and Or(OR(...,NOT(e),...), e) to TRUE
         return(TRUE);
     }
     else if (other is Disj)
     {
         HashList <PathCond> result = new HashList <PathCond>();
         result.AddAll(conds);
         foreach (PathCond cond in ((Disj)other).conds)
         {
             if (cond is CachedAtom && conds.Contains((cond as CachedAtom).Negate()))
             {
                 // Reduce Or(OR(...,e,...),OR(...,NOT(e),...)) to TRUE
                 // and    Or(OR(...,NOT(e),...),OR(...,e,...)) to TRUE
                 return(TRUE);
             }
             result.Add(cond);
         }
         return(Disj.Make(result.ToArray()));
     }
     else if (other is Conj)
     {
         if (((Conj)other).conds.Contains(this))
         {
             // Reduce (pi | (p1 & ... & pn)) to pi
             return(this);
         }
         else
         {
             if (((Conj)other).conds.Any(cond => conds.Contains(cond)))
             {
                 return(this);
             }
         }
         return(Disj.Make(AddItem(this.conds, other)));
     }
     else
     {
         return(Disj.Make(AddItem(this.conds, other)));
     }
 }
Ejemplo n.º 8
0
        internal IType RegisterArrayType(IType elementType)
        {
            var type = TypeFactory.MakeArray(elementType);

            if (!_constructedTypes.Contains(type))
            {
                _constructedTypes.Add(type);
            }
            return(type);
        }
Ejemplo n.º 9
0
        public void Test_Contains_After_Remove()
        {
            var list = new HashList <int>
            {
                2
            };

            list.Remove(2);

            Assert.AreEqual(false, list.Contains(2), "#0");
        }
        /// <summary>
        /// Add a <see cref="Constraint"/> to the world.
        /// </summary>
        /// <param name="constraint">The constraint which should be removed.</param>
        public void AddConstraint(Constraint constraint)
        {
            if (constraints.Contains(constraint))
            {
                throw new ArgumentException("The constraint was already added to the world.", "constraint");
            }

            constraints.Add(constraint);

            islands.ConstraintCreated(constraint);

            events.RaiseAddedConstraint(constraint);
        }
        /// <summary>
        /// Adds a <see cref="RigidBody"/> to the world.
        /// </summary>
        /// <param name="body">The body which should be added.</param>
        public void AddBody(RigidBody body)
        {
            if (body == null)
            {
                throw new ArgumentNullException("body", "body can't be null.");
            }
            if (rigidBodies.Contains(body))
            {
                throw new ArgumentException("The body was already added to the world.", "body");
            }

            events.RaiseAddedRigidBody(body);

            this.CollisionSystem.AddEntity(body);

            rigidBodies.Add(body);
        }
Ejemplo n.º 12
0
        public virtual void AddItem(C item)
        {
            PropertyDescriptor prop = TypeDescriptor.GetProperties(item).Find("Oid", false);

            this.Add(item);

            long oid = (long)prop.GetValue(item);

            while (HashList.Contains(oid) && item.IsNew)
            {
                Random r = new Random();
                oid      = (long)r.Next();
                item.Oid = oid;
            }

            HashList.Add(oid, item);
        }
Ejemplo n.º 13
0
        public string GenerateString()
        {
            string s;

            do
            {
                if (_stringIndex < _strings.Count)
                {
                    s = _strings[_stringIndex];
                }
                else
                {
                    s = GenerateNextString();
                }

                _stringIndex++;
            }while (_existingStrings.Contains(s));

            return(s);
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Adds or modifies object in display list.
        /// </summary>
        /// <param name="obj">The object to add or modify.</param>
        /// <param name="transform">The transformation of object.</param>
        public void PlaceObject(ISwfDisplayObject obj, Matrix transform)
        {
            var tag = obj as SwfTag;

            if (tag == null)
            {
                throw new ArgumentException();
            }

            if (_displayList.Contains(obj))
            {
                Tags.Add(new SwfTagPlaceObject2(obj, transform, SwfPlaceMode.Modify));
            }
            else
            {
                obj.Depth = (ushort)(_displayList.Count + 1);
                _displayList.Add(obj);
                Tags.Add(new SwfTagPlaceObject2(obj, transform, SwfPlaceMode.New));
            }
        }
Ejemplo n.º 15
0
        void Add(BaseLogData data)
        {
            if (DatasSet.Contains(data))
            {
                return;
            }
            GameObject  go      = GOPool.Spawn();
            BaseLogItem logItem = go.GetComponent <BaseLogItem>();

            logItem.CancleInit();
            logItem.Init(new UButtonData
            {
                OnShowActive = OnAlertShow,
            });
            logItem.SetID(data.ID);
            logItem.Show(true, true);
            logItem.NameText           = data.GetDesc();
            logItem.RectTrans.position = StartPos.position;
            ActiveItems.Add(logItem);
            DatasSet.Add(data);
        }
Ejemplo n.º 16
0
        /// <summary>Load all tokens from the token source and put in tokens.
        /// This is done upon first LT request because you might want to
        /// set some token type / channel overrides before filling buffer.
        /// </summary>
        protected virtual void FillBuffer()
        {
            int    index = 0;
            IToken t     = tokenSource.NextToken();

            while ((t != null) && (t.Type != (int)Antlr.Runtime.CharStreamConstants.EOF))
            {
                bool discard = false;
                // is there a channel override for token type?
                if (channelOverrideMap != null)
                {
                    object channelI = channelOverrideMap[(int)t.Type];
                    if (channelI != null)
                    {
                        t.Channel = (int)channelI;
                    }
                }
                if (discardSet != null && discardSet.Contains(t.Type.ToString()))
                {
                    discard = true;
                }
                else if (discardOffChannelTokens && t.Channel != this.channel)
                {
                    discard = true;
                }
                if (!discard)
                {
                    t.TokenIndex = index;
                    tokens.Add(t);
                    index++;
                }
                t = tokenSource.NextToken();
            }
            // leave p pointing at first token on channel
            p = 0;
            p = SkipOffTokenChannels(p);
        }
Ejemplo n.º 17
0
        private void AddNode(HashList <FullCellAddr> sorted, FullCellAddr node)
        {
            HashSet <FullCellAddr> precedents;

            if (GetPrecedents(node, out precedents))
            {
                Cell cell;
                foreach (FullCellAddr precedent in precedents)
                {
                    // By including only non-input Formula and ArrayFormula cells, we avoid that
                    // constant cells get stored in local variables.  The result will not contain
                    // constants cells (and will contain an input cell only if it is also the
                    // output cell), so must the raw graph to find all cells belonging to an SDF.
                    if (!sorted.Contains(precedent) &&
                        precedent.TryGetCell(out cell) &&
                        (cell is Formula || cell is ArrayFormula) &&
                        !inputCellSet.Contains(precedent))
                    {
                        AddNode(sorted, precedent);
                    }
                }
            }
            sorted.Add(node);             // Last in HashList
        }
Ejemplo n.º 18
0
    // Use this for initialization
    void Start()
    {
        list = new List <HashList <int> >();
        for (int i = 0; i < 1000; i++)
        {
            var hash = new HashList <int>(15000);
            for (int j = 0; j < 10000; j++)
            {
                hash.Add(Random.Range(int.MinValue, int.MaxValue));
            }
        }

        var set = new HashList <int>();

        Debug.Log("Add 1 " + set.Add(1));
        Debug.Log("Add 1 " + set.Add(1));
        set.Add(30000);
        set.Add(444);
        Debug.Log("Add 5555 " + set.Add(5555));
        set.Add(500000);
        set.Add(364892679);

        set.Remove(444);
        Debug.Log("Set contains 444 = " + set.Contains(444));
        Debug.Log("Size = " + set.Count);

        foreach (var i in set)
        {
            Debug.Log("Set contains " + i + " = " + set.Contains(i));
        }


        Debug.Log("Set contains 11 = " + set.Contains(11));
        Debug.Log("Set contains 23 = " + set.Contains(23));
        Debug.Log("Set contains 16 = " + set.Contains(16));
        Debug.Log("Set contains 32 = " + set.Contains(32));
        Debug.Log("Set contains 33 = " + set.Contains(33));
    }
Ejemplo n.º 19
0
    // Use this for initialization
    void Start ()
    {
        list = new List<HashList<int>>();
        for (int i = 0; i < 1000; i++)
        {
            var hash = new HashList<int>(15000);
            for (int j = 0; j < 10000; j++)
            {
                hash.Add(Random.Range(int.MinValue, int.MaxValue));
            }
        }

        var set = new HashList<int>();
        Debug.Log("Add 1 " + set.Add(1));
        Debug.Log("Add 1 " + set.Add(1));
        set.Add(30000);
        set.Add(444);
        Debug.Log("Add 5555 " + set.Add(5555));
        set.Add(500000);
        set.Add(364892679);

        set.Remove(444);
        Debug.Log("Set contains 444 = " + set.Contains(444));
        Debug.Log("Size = " + set.Count);

        foreach (var i in set)
        {
            Debug.Log("Set contains " + i + " = " + set.Contains(i));
        }


        Debug.Log("Set contains 11 = " + set.Contains(11));
        Debug.Log("Set contains 23 = " + set.Contains(23));
        Debug.Log("Set contains 16 = " + set.Contains(16));
        Debug.Log("Set contains 32 = " + set.Contains(32));
        Debug.Log("Set contains 33 = " + set.Contains(33));
    }
Ejemplo n.º 20
0
        static bool SearchHash(uint hash, bool reverse, bool printFileList, System.Text.RegularExpressions.Regex regexpFilterString)
        {
            bool found = false;

            // walk the hash lists
            foreach (var pair in _HashFiles)
            {
                if (pair.Value.Contains(hash))
                {
                    if (reverse == false)
                    {
                        Console.WriteLine("  hash found in {0}", Path.GetFileNameWithoutExtension(pair.Key));
                    }
                    else
                    {
                        Console.WriteLine("  reverse hash found in {0}", Path.GetFileNameWithoutExtension(pair.Key));
                    }
                    found = true;
                }
            }

            // ask _Files for a name
            if (_Files.Contains(hash))
            {
                if (reverse == false)
                {
                    Console.WriteLine("  found file that matches: {0}", _Files[hash]);
                }
                else
                {
                    Console.WriteLine("  found file that matches for reverse hash: {0}", _Files[hash]);
                }
                found = true;
            }

            // ask _Name for a name
            if (_Names.Contains(hash))
            {
                if (reverse == false)
                {
                    Console.WriteLine("  found string: {0}", _Names[hash]);
                }
                else
                {
                    Console.WriteLine("  found string for reverse hash: {0}", _Names[hash]);
                }
                found = true;
            }

            // lookup the file list for this hash:
            if (_HashFileDict.ContainsKey(hash))
            {
                var l = _HashFileDict[hash];
                if (printFileList || l.Count <= 3)
                {
                    foreach (var h in l)
                    {
                        string fileName = _FileHashDict[h];
                        if (regexpFilterString != null && regexpFilterString.IsMatch(fileName) == false)
                        {
                            continue;
                        }
                        if (reverse == false)
                        {
                            Console.WriteLine("  used in {0}", fileName);
                        }
                        else
                        {
                            Console.WriteLine("  reverse used in {0}", fileName);
                        }
                    }
                }
                else if (l.Count > 0)
                {
                    if (reverse == false)
                    {
                        Console.WriteLine("  appears in {0} files. (prefix the query with : to print the list)", l.Count, hash);
                    }
                    else
                    {
                        Console.WriteLine("  reverse appears in {0} files. (prefix the query with : to print the list)", l.Count, hash);
                    }
                }
            }
            return(found);
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Find or create an output file for a corresponding input file
        /// </summary>
        /// <param name="InputFile">The input file</param>
        /// <param name="IncludeStack">The current include stack</param>
        /// <param name="OutputFiles">List of output files</param>
        /// <param name="OutputFileLookup">Mapping from source file to output file</param>
        /// <returns>The new or existing output file</returns>
        static OutputFile FindOrCreateOutputFile(List <SourceFile> InputFileStack, Dictionary <SourceFile, SourceFile> CppFileToHeaderFile, HashList <OutputFile> PreviousFiles, Dictionary <SourceFile, OutputFile> OutputFileLookup, Dictionary <Symbol, OutputFile> FwdSymbolToHeader, bool bMakeStandalone, bool bUseOriginalIncludes, LineBasedTextWriter Log)
        {
            // Get the file at the top of the stack
            SourceFile InputFile = InputFileStack[InputFileStack.Count - 1];

            // Try to find an existing file
            OutputFile OutputFile;

            if (OutputFileLookup.TryGetValue(InputFile, out OutputFile))
            {
                if (OutputFile == null)
                {
                    throw new Exception("Circular include dependencies are not allowed.");
                }
                foreach (OutputFile IncludedFile in OutputFile.OriginalIncludedFiles.Where(x => !PreviousFiles.Contains(x)))
                {
                    PreviousFiles.Add(IncludedFile);
                }
            }
            else
            {
                // Add a placeholder entry in the output file lookup, so we can detect circular include dependencies
                OutputFileLookup[InputFile] = null;

                // Duplicate the list of previously included files, so we can construct the
                List <OutputFile> PreviousFilesCopy = new List <OutputFile>(PreviousFiles);

                // Build a list of includes for this file. First include is a placeholder for any missing includes that need to be inserted.
                List <OutputFileInclude> Includes = new List <OutputFileInclude>();
                if ((InputFile.Flags & SourceFileFlags.External) == 0)
                {
                    for (int MarkupIdx = 0; MarkupIdx < InputFile.Markup.Length; MarkupIdx++)
                    {
                        PreprocessorMarkup Markup = InputFile.Markup[MarkupIdx];
                        if (Markup.IsActive && Markup.IncludedFile != null && (Markup.IncludedFile.Flags & SourceFileFlags.Inline) == 0 && Markup.IncludedFile.Counterpart == null)
                        {
                            InputFileStack.Add(Markup.IncludedFile);
                            OutputFile IncludeFile = FindOrCreateOutputFile(InputFileStack, CppFileToHeaderFile, PreviousFiles, OutputFileLookup, FwdSymbolToHeader, bMakeStandalone, bUseOriginalIncludes, Log);
                            InputFileStack.RemoveAt(InputFileStack.Count - 1);
                            Includes.Add(new OutputFileInclude(MarkupIdx, IncludeFile));
                        }
                    }
                }

                // Find the matching header file
                OutputFile HeaderFile = null;
                if ((InputFile.Flags & SourceFileFlags.TranslationUnit) != 0)
                {
                    SourceFile CandidateHeaderFile;
                    if (CppFileToHeaderFile.TryGetValue(InputFile, out CandidateHeaderFile) && (CandidateHeaderFile.Flags & SourceFileFlags.Standalone) != 0)
                    {
                        OutputFileLookup.TryGetValue(CandidateHeaderFile, out HeaderFile);
                    }
                }

                // Create the output file.
                if ((InputFile.Flags & SourceFileFlags.Output) != 0 && !bUseOriginalIncludes)
                {
                    OutputFile = CreateOptimizedOutputFile(InputFile, HeaderFile, PreviousFilesCopy, Includes, InputFileStack, FwdSymbolToHeader, bMakeStandalone, Log);
                }
                else
                {
                    OutputFile = CreatePassthroughOutputFile(InputFile, Includes, Log);
                }

                // Replace the null entry in the output file lookup that we added earlier
                OutputFileLookup[InputFile] = OutputFile;

                // Add this file to the list of included files
                PreviousFiles.Add(OutputFile);

                // If the output file dependends on something on the stack, make sure it's marked as pinned
                if ((InputFile.Flags & SourceFileFlags.Pinned) == 0)
                {
                    SourceFragment Dependency = OutputFile.Dependencies.FirstOrDefault(x => InputFileStack.Contains(x.File) && x.File != InputFile);
                    if (Dependency != null)
                    {
                        throw new Exception(String.Format("'{0}' is not marked as pinned, but depends on '{1}' which includes it", InputFile.Location.GetFileName(), Dependency.UniqueName));
                    }
                }
            }
            return(OutputFile);
        }
Ejemplo n.º 22
0
 public void ContainsTest()
 {
     Assert.IsTrue(_list1.Contains(22));
     Assert.IsFalse(_list1.Contains(23));
 }
Ejemplo n.º 23
0
        /// <summary>
        /// Write out an optimized file to the given location
        /// </summary>
        /// <param name="IncludePaths">Base directories for relative include paths</param>
        /// <param name="SystemIncludePaths">Base directories for system include paths</param>
        /// <param name="Writer">Writer for the output text</param>
        public void Write(IEnumerable <DirectoryReference> IncludePaths, IEnumerable <DirectoryReference> SystemIncludePaths, TextWriter Writer, bool bRemoveForwardDeclarations, TextWriter Log)
        {
            // Write the file header
            TextLocation LastLocation = Text.Start;

            // Write the standalone includes
            if (MissingIncludes.Count > 0)
            {
                TextLocation BoilerplateLocation = (BodyMinIdx == Markup.Length || (Markup[BodyMinIdx].Type != PreprocessorMarkupType.Include && BodyMinIdx > 0))? Markup[BodyMinIdx - 1].EndLocation : Markup[BodyMinIdx].Location;
                WriteLines(Text, LastLocation, BoilerplateLocation, Writer);
                LastLocation = BoilerplateLocation;

                if (LastLocation.LineIdx > 0 && Text.Lines[LastLocation.LineIdx - 1].TrimEnd().Length > 0)
                {
                    if (LastLocation.LineIdx + 1 < Text.Lines.Length && Text.Lines[LastLocation.LineIdx].TrimEnd().Length == 0 && Text.Lines[LastLocation.LineIdx + 1].TrimEnd().Length == 0)
                    {
                        LastLocation.LineIdx++;
                    }
                    Writer.WriteLine();
                }
                foreach (SourceFile MissingInclude in MissingIncludes)
                {
                    string IncludeText = FormatInclude(Location.Directory, MissingInclude.Location, IncludePaths, SystemIncludePaths, Log);
                    Writer.WriteLine("#include {0}", IncludeText);
                }
            }

            // Figure out before which markup object to write forward declarations, skipping over all the includes at the start of the file
            int ForwardDeclarationsBeforeMarkupIdx = -1;

            if ((Flags & SourceFileFlags.TranslationUnit) == 0)
            {
                int ConditionDepth = 0;
                for (int MarkupIdx = BodyMinIdx; MarkupIdx < Markup.Length; MarkupIdx++)
                {
                    if (ConditionDepth == 0)
                    {
                        ForwardDeclarationsBeforeMarkupIdx = MarkupIdx;
                    }
                    if (Markup[MarkupIdx].Type == PreprocessorMarkupType.Text)
                    {
                        break;
                    }
                    ConditionDepth += Markup[MarkupIdx].GetConditionDepthDelta();
                }
            }

            // Write all the other markup
            for (int MarkupIdx = BodyMinIdx; MarkupIdx < Markup.Length; MarkupIdx++)
            {
                PreprocessorMarkup ThisMarkup = Markup[MarkupIdx];

                // Write the forward declarations
                if (MarkupIdx == ForwardDeclarationsBeforeMarkupIdx)
                {
                    // Write out at least up to the end of the last markup
                    if (MarkupIdx > 0 && LastLocation <= Markup[MarkupIdx - 1].EndLocation)
                    {
                        WriteLines(Text, LastLocation, Markup[MarkupIdx - 1].EndLocation, Writer);
                        LastLocation = Markup[MarkupIdx - 1].EndLocation;
                    }

                    // Skip a blank line in the existing text.
                    TextLocation NewLastLocation = LastLocation;
                    if (LastLocation.LineIdx < Text.Lines.Length && String.IsNullOrWhiteSpace(Text.Lines[LastLocation.LineIdx]))
                    {
                        NewLastLocation = new TextLocation(LastLocation.LineIdx + 1, 0);
                    }

                    // Merge all the existing forward declarations with the new set.
                    HashSet <string> PreviousForwardDeclarations = new HashSet <string>();
                    while (NewLastLocation.LineIdx < Text.Lines.Length)
                    {
                        string TrimLine = Text.Lines[NewLastLocation.LineIdx].Trim();
                        if (TrimLine.Length > 0 && !TrimLine.Equals("// Forward declarations", StringComparison.InvariantCultureIgnoreCase) && !TrimLine.Equals("// Forward declarations.", StringComparison.InvariantCultureIgnoreCase))
                        {
                            // Create a token reader for the current line
                            TokenReader Reader = new TokenReader(Text, new TextLocation(NewLastLocation.LineIdx, 0), new TextLocation(NewLastLocation.LineIdx, Text.Lines[NewLastLocation.LineIdx].Length));

                            // Read it into a buffer
                            List <Token> Tokens = new List <Token>();
                            while (Reader.MoveNext())
                            {
                                Tokens.Add(Reader.Current);
                            }

                            // Check it matches the syntax for a forward declaration, and add it to the list if it does
                            if (Tokens.Count == 3 && (Tokens[0].Text == "struct" || Tokens[0].Text == "class") && Tokens[1].Type == TokenType.Identifier && Tokens[2].Text == ";")
                            {
                                PreviousForwardDeclarations.Add(String.Format("{0} {1};", Tokens[0].Text, Tokens[1].Text));
                            }
                            else if (Tokens.Count == 4 && Tokens[0].Text == "enum" && Tokens[1].Text == "class" && Tokens[2].Type == TokenType.Identifier && Tokens[3].Text == ";")
                            {
                                PreviousForwardDeclarations.Add(String.Format("enum class {0};", Tokens[2].Text));
                            }
                            else if (Tokens.Count == 6 && Tokens[0].Text == "enum" && Tokens[1].Text == "class" && Tokens[2].Type == TokenType.Identifier && Tokens[3].Text == ":" && Tokens[4].Type == TokenType.Identifier && Tokens[5].Text == ";")
                            {
                                PreviousForwardDeclarations.Add(String.Format("enum class {0} : {1};", Tokens[2].Text, Tokens[4].Text));
                            }
                            else if (ForwardDeclarations.Contains(Text.Lines[NewLastLocation.LineIdx]))
                            {
                                PreviousForwardDeclarations.Add(Text.Lines[NewLastLocation.LineIdx]);
                            }
                            else
                            {
                                break;
                            }
                        }
                        NewLastLocation = new TextLocation(NewLastLocation.LineIdx + 1, 0);
                    }

                    // Create a full list of new forward declarations, combining with the ones that are already there. Normally we optimize with the forward declarations present,
                    // so we shouldn't remove any unless running a specific pass designed to do so.
                    HashSet <string> MergedForwardDeclarations = new HashSet <string>(ForwardDeclarations);
                    if (!bRemoveForwardDeclarations)
                    {
                        MergedForwardDeclarations.UnionWith(PreviousForwardDeclarations);
                    }

                    // Write them out
                    if (MergedForwardDeclarations.Count > 0)
                    {
                        Writer.WriteLine();
                        foreach (string ForwardDeclaration in MergedForwardDeclarations.Distinct().OrderBy(x => GetForwardDeclarationSortKey(x)).ThenBy(x => x))
                        {
                            Writer.WriteLine("{0}{1}", GetIndent(MarkupIdx), ForwardDeclaration);
                        }
                        Writer.WriteLine();
                        LastLocation = NewLastLocation;
                    }
                    else if (PreviousForwardDeclarations.Count > 0)
                    {
                        Writer.WriteLine();
                        LastLocation = NewLastLocation;
                    }
                }

                // Write the includes
                if (ThisMarkup.Type == PreprocessorMarkupType.Include && ThisMarkup.IsActive && !ThisMarkup.IsInlineInclude())
                {
                    // Write up to the start of this include
                    WriteLines(Text, LastLocation, ThisMarkup.Location, Writer);

                    // Get the original include text. Some modules - particularly editor modules - include headers from other modules based from Engine/Source which are not listed as dependencies. If
                    // the original include is based from a shallower directory than the one we would include otherwise, we'll use that instead.
                    string OriginalIncludeText = null;
                    if (ThisMarkup.Tokens.Count == 1)
                    {
                        OriginalIncludeText = ThisMarkup.Tokens[0].Text.Replace('\\', '/');
                    }

                    // Write the replacement includes
                    foreach (SourceFile OutputIncludedFile in ThisMarkup.OutputIncludedFiles)
                    {
                        string IncludeText = FormatInclude(Location.Directory, OutputIncludedFile.Location, IncludePaths, SystemIncludePaths, Log);
                        if (OutputIncludedFile == ThisMarkup.IncludedFile && Rules.IsExternalIncludeMacro(ThisMarkup.Tokens))
                        {
                            IncludeText = Token.Format(ThisMarkup.Tokens);
                        }
                        else if (OutputIncludedFile == ThisMarkup.IncludedFile && (OutputIncludedFile.Flags & SourceFileFlags.External) != 0)
                        {
                            IncludeText = OriginalIncludeText;
                        }
                        else if (OriginalIncludeText != null && (Flags & SourceFileFlags.TranslationUnit) == 0 && OriginalIncludeText.EndsWith(IncludeText.TrimStart('\"'), StringComparison.InvariantCultureIgnoreCase) && (OriginalIncludeText.StartsWith("\"Runtime/", StringComparison.InvariantCultureIgnoreCase) || OriginalIncludeText.StartsWith("\"Developer/", StringComparison.InvariantCultureIgnoreCase) || OriginalIncludeText.StartsWith("\"Editor/", StringComparison.InvariantCultureIgnoreCase)))
                        {
                            IncludeText = OriginalIncludeText;
                        }
                        Writer.WriteLine("{0}#include {1}", GetIndent(MarkupIdx), IncludeText);
                    }

                    // Copy any formatting
                    if (ThisMarkup.EndLocation.LineIdx > ThisMarkup.Location.LineIdx + 1)
                    {
                        WriteLines(Text, new TextLocation(ThisMarkup.Location.LineIdx + 1, 0), ThisMarkup.EndLocation, Writer);
                    }

                    // Update the location to the start of the next line
                    LastLocation = new TextLocation(ThisMarkup.Location.LineIdx + 1, 0);
                }
            }

            // Write to the end of the file
            WriteLines(Text, LastLocation, Text.End, Writer);
        }
Ejemplo n.º 24
0
        public static void Main(string[] args)
        {
            bool   showHelp       = false;
            string currentProject = null;

            var options = new OptionSet()
            {
                { "h|help", "show this message and exit", v => showHelp = v != null },
                { "p|project=", "override current project", v => currentProject = v },
            };

            List <string> extras;

            try
            {
                extras = options.Parse(args);
            }
            catch (OptionException e)
            {
                Console.Write("{0}: ", GetExecutableName());
                Console.WriteLine(e.Message);
                Console.WriteLine("Try `{0} --help' for more information.", GetExecutableName());
                return;
            }

            if (extras.Count != 0 || showHelp == true)
            {
                Console.WriteLine("Usage: {0} [OPTIONS]+", GetExecutableName());
                Console.WriteLine();
                Console.WriteLine("Options:");
                options.WriteOptionDescriptions(Console.Out);
                return;
            }

            Console.WriteLine("Loading project...");

            var manager = Manager.Load(currentProject);

            if (manager.ActiveProject == null)
            {
                Console.WriteLine("Nothing to do: no active project loaded.");
                return;
            }

            var project = manager.ActiveProject;
            var version = -1;
            HashList <ulong> knownHashes  = null;
            HashList <ulong> subFatHashes = null;

            var installPath = project.InstallPath;
            var listsPath   = project.ListsPath;

            if (installPath == null)
            {
                Console.WriteLine("Could not detect install path.");
                return;
            }

            if (listsPath == null)
            {
                Console.WriteLine("Could not detect lists path.");
                return;
            }

            Console.WriteLine("Searching for archives...");
            var fatPaths = new List <string>();

            fatPaths.AddRange(Directory.GetFiles(installPath, "*.fat", SearchOption.AllDirectories));

            var outputPaths = new List <string>();

            var breakdown = new Breakdown();
            var tracking  = new Tracking();

            Console.WriteLine("Processing...");
            for (int i = 0; i < fatPaths.Count; i++)
            {
                var fatPath = fatPaths[i];
                var datPath = Path.ChangeExtension(fatPath, ".dat");

                var outputPath = GetListPath(installPath, fatPath);
                if (outputPath == null)
                {
                    throw new InvalidOperationException();
                }

                Console.WriteLine(outputPath);
                outputPath = Path.Combine(listsPath, outputPath);

                if (outputPaths.Contains(outputPath) == true)
                {
                    throw new InvalidOperationException();
                }

                outputPaths.Add(outputPath);

                if (File.Exists(fatPath + ".bak") == true)
                {
                    fatPath += ".bak";
                    datPath += ".bak";
                }

                var fat = new BigFile();
                using (var input = File.OpenRead(fatPath))
                {
                    fat.Deserialize(input);
                }

                if (version == -1)
                {
                    version      = fat.Version;
                    knownHashes  = manager.LoadListsFileNames(fat.Version);
                    subFatHashes = manager.LoadListsSubFatNames(fat.Version);
                }
                else if (version != fat.Version)
                {
                    throw new InvalidOperationException();
                }

                if (knownHashes == null ||
                    subFatHashes == null)
                {
                    throw new InvalidOperationException();
                }

                HandleEntries(fat.Entries.Select(e => e.NameHash).Distinct(),
                              knownHashes,
                              tracking,
                              breakdown,
                              outputPath);

                using (var input = File.OpenRead(datPath))
                {
                    foreach (var headerEntry in fat.Entries.Where(e => subFatHashes.Contains(e.NameHash) == true))
                    {
                        var subFat = new SubFatFile();
                        using (var temp = new MemoryStream())
                        {
                            Big.EntryDecompression.Decompress(headerEntry, input, temp);
                            temp.Position = 0;
                            subFat.Deserialize(temp, fat);
                        }

                        var matchingSubFats = fat.SubFats
                                              .Where(sf => subFat.Entries.SequenceEqual(sf.Entries))
                                              .ToArray();

                        if (matchingSubFats.Length == 0)
                        {
                            continue;
                        }

                        if (matchingSubFats.Length > 1)
                        {
                            throw new InvalidOperationException();
                        }

                        var subfatPath = GetListPath(installPath,
                                                     fatPath,
                                                     FilterEntryName(subFatHashes[headerEntry.NameHash]));
                        if (subfatPath == null)
                        {
                            throw new InvalidOperationException();
                        }

                        Console.WriteLine(subfatPath);
                        subfatPath = Path.Combine(listsPath, subfatPath);

                        HandleEntries(subFat.Entries.Select(e => e.NameHash),
                                      knownHashes,
                                      tracking,
                                      breakdown,
                                      subfatPath);
                    }
                }
            }

            using (var output = new StreamWriter(Path.Combine(Path.Combine(listsPath, "files"), "status.txt")))
            {
                output.WriteLine("{0}",
                                 new Breakdown()
                {
                    Known = tracking.Names.Distinct().Count(),
                    Total = tracking.Hashes.Distinct().Count(),
                });
            }
        }
Ejemplo n.º 25
0
        /// <summary>
        /// type_method = [ "static" ], signature, method_name, [ ":", signature, identifier, { ",", signature, identifier } ], "{", { local_stmt }, "}" ;
        /// </summary>
        private void ParseTypeMethod()
        {
            // ? "static"
              bool isStatic = false;
              if (PeekLexem(LexemType.Static))
              {
            SkipLexem();
            isStatic = true;
              }

              // signature
              var methodType = ParseSignature();

              // <method_name>
              if (!PeekLexem(LexemType.Identifier)) Error(Resources.errMethodNameExpected);
              var methodName = GetLexem();
              if (ReservedMethods.ContainsKey(methodName.Data) && ReservedMethods[methodName.Data] != methodType.Signature)
            Error(String.Format(Resources.errSpecialIncorrectReturnType, methodName.Data, ReservedMethods[methodName.Data]));

              // validate static constructor
              if (methodName.Data == "construct" && isStatic)
            Error(String.Format(Resources.errStaticConstructor, Compiler.Emitter.CurrentType.Name));

              SkipLexem();

              HashList<ParameterNode> parameters = null;
              // ? "(", params, ")"
              if(PeekLexem(LexemType.ParenOpen))
              {
            SkipLexem();

            parameters = new HashList<ParameterNode>();
            var idx = 0;

            while(!PeekLexem(LexemType.ParenClose, LexemType.EOF))
            {
              // separator
              if(idx > 0)
              {
            if (!PeekLexem(LexemType.Comma)) Error(Resources.errCommaExpected);
            SkipLexem();
              }

              // signature
              var paramType = ParseSignature();
              // <name>
              if (!PeekLexem(LexemType.Identifier)) Error(Resources.errParameterNameExpected);
              var paramName = GetLexem();
              if (parameters.Contains(paramName.Data)) Error(String.Format(Resources.errParameterNameDuplicated, paramName.Data));
              parameters.Add(paramName.Data, new ParameterNode(paramName.Data, paramType, idx));
              SkipLexem();
              idx++;
            }

            // ")"
            if (!PeekLexem(LexemType.ParenClose))
              Error(Resources.errParenExpected);
            SkipLexem();
              }

              MethodNode method;
              if (methodName.Data == "construct")
            method = Compiler.Emitter.CreateCtor(Compiler.Emitter.CurrentType, parameters);
              else
            method = Compiler.Emitter.CreateMethod(Compiler.Emitter.CurrentType, methodName.Data, methodType, parameters, isStatic);

              method.Lexem = methodName;
              Compiler.Emitter.CurrentMethod = method;

              // lookahead "{"
              if (!PeekLexem(LexemType.CurlyOpen)) Error(Resources.errMethodCurlyBrace);

              method.Body = ParseCodeBlock();

              Compiler.Emitter.CurrentMethod = null;
        }
Ejemplo n.º 26
0
        /// <summary>
        /// Calculate the route from start to end.
        /// </summary>
        /// <param name="start">Start.</param>
        /// <param name="end">End.</param>
        public void Route(T start, T end, List <T> route)
        {
            route.Clear();
            if (start == null || end == null)
            {
                return;
            }

            for (int i = 0, nodesLength = nodes.Length; i < nodesLength; i++)
            {
                var s = nodes[i];
                g[s]      = 0f;
                parent[s] = null;
                inPath[s] = false;
            }
            openset.Clear();
            closedset.Clear();
            path.Clear();

            var current = start;

            openset.Add(current);
            while (openset.Count > 0)
            {
                current = openset[0];
                for (var i = 1; i < openset.Count; i++)
                {
                    var d = g[current].CompareTo(g[openset[i]]);
                    if (d < 0)
                    {
                        current = openset[i];
                    }
                }
                //openset.Sort ((a,b) => g [a].CompareTo (g [b]));
                current = openset[0];
                if (current == end)
                {
                    while (parent[current] != null)
                    {
                        path.Enqueue(current);
                        inPath[current] = true;
                        current         = parent[current];
                        if (path.Count >= nodes.Length)
                        {
                            return;
                        }
                    }
                    inPath[current] = true;
                    path.Enqueue(current);
                    while (path.Count > 0)
                    {
                        route.Add(path.Dequeue());
                    }
                    return;
                }
                openset.Remove(current);
                closedset.Add(current);
                var connectedNodes = current.GetConnectedNodes();
                for (int i = 0, connectedNodesCount = connectedNodes.Count; i < connectedNodesCount; i++)
                {
                    var node = connectedNodes[i];
                    if (closedset.Contains(node))
                    {
                        continue;
                    }
                    if (openset.Contains(node))
                    {
                        var new_g = g[current] + current.CalculateMoveCost(node);
                        if (g[node] > new_g)
                        {
                            g[node]      = new_g;
                            parent[node] = current;
                        }
                    }
                    else
                    {
                        g[node]      = g[current] + current.CalculateMoveCost(node);
                        parent[node] = current;
                        openset.Add(node);
                    }
                }
            }
            return;
        }
Ejemplo n.º 27
0
		private void AddNode(HashList<FullCellAddr> sorted, FullCellAddr node) {
			HashSet<FullCellAddr> precedents;
			if (GetPrecedents(node, out precedents)) {
				Cell cell;
				foreach (FullCellAddr precedent in precedents) {
					// By including only non-input Formula and ArrayFormula cells, we avoid that 
					// constant cells get stored in local variables.  The result will not contain 
					// constants cells (and will contain an input cell only if it is also the 
					// output cell), so must the raw graph to find all cells belonging to an SDF.
					if (!sorted.Contains(precedent)
						&& precedent.TryGetCell(out cell)
						&& (cell is Formula || cell is ArrayFormula)
						&& !inputCellSet.Contains(precedent)) {
						AddNode(sorted, precedent);
					}
				}
			}
			sorted.Add(node); // Last in HashList
		}
Ejemplo n.º 28
0
 public bool IsPlayEligible(IEnumerable <WhiteCard> play)
 {
     return(play.Any(c => _triggerCards.Contains(c.Id)) || _triggerContent.Any(tc => play.Any(p => p.ContainsContentFlags(tc))));
 }
Ejemplo n.º 29
0
 public bool Contains(T item)
 {
     return(hashset.Contains(item));
 }