Example #1
0
        private static bool ContainsAnyImplementation(string source, IEnumerable<char> characters)
        {
            Debug.Assert(source != null, "source != null");
            Debug.Assert(characters != null, "characters != null");

            var hs = new HashSet<char>(characters);
            return !hs.IsEmpty() && source.Any(hs.Contains);
        }
        /// <summary>
        /// Creates a new compilation without the specified syntax trees. Preserves metadata info for use with trees
        /// added later. 
        /// </summary>
        public new CSharpCompilation RemoveSyntaxTrees(IEnumerable<SyntaxTree> trees)
        {
            using (Logger.LogBlock(FunctionId.CSharp_Compilation_RemoveSyntaxTrees, message: this.AssemblyName))
            {
                if (trees == null)
                {
                    throw new ArgumentNullException("trees");
                }

                if (trees.IsEmpty())
                {
                    return this;
                }

                bool referenceDirectivesChanged = false;
                var removeSet = new HashSet<SyntaxTree>();
                var declMap = rootNamespaces;
                var declTable = declarationTable;
                foreach (var tree in trees.Cast<CSharpSyntaxTree>())
                {
                    RemoveSyntaxTreeFromDeclarationMapAndTable(tree, ref declMap, ref declTable, ref referenceDirectivesChanged);
                    removeSet.Add(tree);
                }

                Debug.Assert(!removeSet.IsEmpty());

                // We're going to have to revise the ordinals of all
                // trees after the first one removed, so just build
                // a new map.
                var ordinalMap = ImmutableDictionary.Create<SyntaxTree, int>();
                var builder = ArrayBuilder<SyntaxTree>.GetInstance();
                int i = 0;
                foreach (var tree in this.SyntaxTrees)
                {
                    if (!removeSet.Contains(tree))
                    {
                        builder.Add(tree);
                        ordinalMap = ordinalMap.Add(tree, i++);
                    }
                }

                return UpdateSyntaxTrees(builder.ToImmutableAndFree(), ordinalMap, declMap, declTable, referenceDirectivesChanged);
            }
        }
Example #3
0
		/// <exception cref="System.IO.IOException"></exception>
		private ObjectDirectory.CachedPackList ScanCachedPacks(ObjectDirectory.CachedPackList
			 old)
		{
			FileSnapshot s = FileSnapshot.Save(cachedPacksFile);
			byte[] buf;
			try
			{
				buf = IOUtil.ReadFully(cachedPacksFile);
			}
			catch (FileNotFoundException)
			{
				buf = new byte[0];
			}
			if (old != null && old.snapshot.Equals(s) && Arrays.Equals(old.raw, buf))
			{
				old.snapshot.SetClean(s);
				return old;
			}
			AList<LocalCachedPack> list = new AList<LocalCachedPack>(4);
			ICollection<ObjectId> tips = new HashSet<ObjectId>();
			int ptr = 0;
			while (ptr < buf.Length)
			{
				if (buf[ptr] == '#' || buf[ptr] == '\n')
				{
					ptr = RawParseUtils.NextLF(buf, ptr);
					continue;
				}
				if (buf[ptr] == '+')
				{
					tips.AddItem(ObjectId.FromString(buf, ptr + 2));
					ptr = RawParseUtils.NextLF(buf, ptr + 2);
					continue;
				}
				IList<string> names = new AList<string>(4);
				while (ptr < buf.Length && buf[ptr] == 'P')
				{
					int end = RawParseUtils.NextLF(buf, ptr);
					if (buf[end - 1] == '\n')
					{
						end--;
					}
					names.AddItem(RawParseUtils.Decode(buf, ptr + 2, end));
					ptr = RawParseUtils.NextLF(buf, end);
				}
				if (!tips.IsEmpty() && !names.IsEmpty())
				{
					list.AddItem(new LocalCachedPack(this, tips, names));
					tips = new HashSet<ObjectId>();
				}
			}
			list.TrimToSize();
			return new ObjectDirectory.CachedPackList(s, Sharpen.Collections.UnmodifiableList
				(list), buf);
		}
Example #4
0
		/// <exception cref="System.IO.IOException"></exception>
		private void RecvWants()
		{
			HashSet<ObjectId> wantIds = new HashSet<ObjectId>();
			bool isFirst = true;
			for (; ; )
			{
				string line;
				try
				{
					line = pckIn.ReadString();
				}
				catch (EOFException eof)
				{
					if (isFirst)
					{
						break;
					}
					throw;
				}
				if (line == PacketLineIn.END)
				{
					break;
				}
				if (!line.StartsWith("want ") || line.Length < 45)
				{
					throw new PackProtocolException(MessageFormat.Format(JGitText.Get().expectedGot, 
						"want", line));
				}
				if (isFirst && line.Length > 45)
				{
					string opt = Sharpen.Runtime.Substring(line, 45);
					if (opt.StartsWith(" "))
					{
						opt = Sharpen.Runtime.Substring(opt, 1);
					}
					foreach (string c in opt.Split(" "))
					{
						options.AddItem(c);
					}
					line = Sharpen.Runtime.Substring(line, 0, 45);
				}
				wantIds.AddItem(ObjectId.FromString(Sharpen.Runtime.Substring(line, 5)));
				isFirst = false;
			}
			if (wantIds.IsEmpty())
			{
				return;
			}
			AsyncRevObjectQueue q = walk.ParseAny(wantIds.AsIterable (), true);
			try
			{
				for (; ; )
				{
					RevObject o;
					try
					{
						o = q.Next();
					}
					catch (IOException error)
					{
						throw new PackProtocolException(MessageFormat.Format(JGitText.Get().notValid, error
							.Message), error);
					}
					if (o == null)
					{
						break;
					}
					if (o.Has(WANT))
					{
					}
					else
					{
						// Already processed, the client repeated itself.
						if (o.Has(ADVERTISED))
						{
							o.Add(WANT);
							wantAll.AddItem(o);
							if (o is RevTag)
							{
								o = walk.Peel(o);
								if (o is RevCommit)
								{
									if (!o.Has(WANT))
									{
										o.Add(WANT);
										wantAll.AddItem(o);
									}
								}
							}
						}
						else
						{
							throw new PackProtocolException(MessageFormat.Format(JGitText.Get().notValid, o.Name
								));
						}
					}
				}
			}
			finally
			{
				q.Release();
			}
		}
            getFuturesStatic(List< string> tickers , string futuresStaticMoniker, ICarbonClient client, string carbonEnv,
            out Tuple<List<Tuple<string, ContractMonths>> /*rootTickers*/, List<string> /*contracts*/> tickerSplitTuple,
            DateTime? vStartDate = null, DateTime? vEndDate = null, List<string> contractSortOrder = null )
        //------------------------------------------------------------------------------------------------
        {

            // Intialisation
            if (tickers == null)
            {
                tickers = new List<string>();
            }
            DateTime startDate, endDate;
            if (vStartDate == null)
            {
                startDate = DateTime.MinValue;
            }
            else
            {
                startDate = vStartDate.Value;
            }

            if (vStartDate == null)
            {
                endDate = DateTime.MaxValue;
            }
            else
            {
                endDate = vEndDate.Value;
            }
            if (contractSortOrder == null)
            {
                contractSortOrder = new List<string>();
            }

            string cacheKey = getCacheKey(tickers, futuresStaticMoniker, startDate, endDate, contractSortOrder);


            // Divide inputs according to whether they should be used for rolling futures or not
            tickerSplitTuple                                = splitRollingFuturesFromRawTickers(tickers);
            List<string> contractTickers                    = tickerSplitTuple.Item2;
            List<Tuple<string, ContractMonths>> rootTickers = tickerSplitTuple.Item1;

            
            // Get Static From cache here if we have it, tickersplittuple has been set.
            Frame<string, string> cachedValue;
            if (StaticCache_.TryGetValue(cacheKey, out cachedValue)) return cachedValue;
            
            // Get all the roots from list
            List< string> rollingFuturesIDs                 = new List<string>();
            foreach (var tup in rootTickers)
            {
                rollingFuturesIDs.Add(tup.Item1);
            }
            
            // Get test sets.
            //      This allows us to map back names used in futures static moniker, to our original inputs
            var bbgTickerMap            = processBBGTickerList(contractTickers); 
            HashSet<string> rollingSet  = new HashSet<string>(rollingFuturesIDs);
            HashSet<string> tickerSet   = new HashSet<string>(bbgTickerMap.Keys.AsEnumerable());

            // Processing inputs
            Frame<string, string> output;
            var rowList = new List<KeyValuePair<int/*id*/, Series<string, object>/*row*/>>();

            var df = client.GetDataFrame(futuresStaticMoniker);
            var tmp = df.ToList();
            var col = tmp[0].Value as List<object>;
            var ind = tmp[1].Value as List<object>;
            var dat = tmp[2].Value as List<object>;

            //Find it's first trade date col
            int firstTradeDtCol = 0;
            int futDeliveryDtCol = 0;
            int typeCol = 0;
            for (int j = 0; j < col.Count; ++j)
            {
                string heading = col[j].ToString();
                if (heading == "fut_first_trade_dt")
                {
                    firstTradeDtCol = j;
                }
                if (heading == "fut_dlv_dt_last")
                {
                    futDeliveryDtCol = j;
                }
                if(heading == "type")
                {
                    typeCol = j;
                }
            }

            //client.getdat
            SeriesBuilder<string> sb;
            int i;
            for (i = 0; i < ind.Count; ++i)
            {
                sb = new SeriesBuilder<string>();
                var data = dat[i] as List<object>;
                var contract = data[typeCol].ToString();
                string index = (string)ind[i];

                if ((tickerSet.IsEmpty() && rollingSet.IsEmpty())
                    || (!tickerSet.Contains(index) && !rollingSet.Contains(contract)))
                {
                    continue;
                }

                DateTime firstTradeDate = DateTime.ParseExact(data[firstTradeDtCol].ToString(), "%dd/%MM/%yyyy", CultureInfo.InvariantCulture);
                DateTime futDeliveryDate = DateTime.ParseExact(data[futDeliveryDtCol].ToString(), "%dd/%MM/%yyyy", CultureInfo.InvariantCulture);
                if (rollingSet.Contains(contract) && (futDeliveryDate < startDate || firstTradeDate > endDate))
                {
                    continue;
                }

                if (bbgTickerMap.ContainsKey(index))
                    sb.Add("ticker", bbgTickerMap[index]);
                else
                    sb.Add("ticker", index); // ignores the mappings, in the rolling contract case

                for (int h = 0; h < col.Count; ++h)
                {
                    sb.Add((string)col[h], data[h]);
                }

                rowList.Add(KeyValue.Create(i, sb.Series)); 
            }

            output = Frame.FromRows(rowList).IndexRows<string>("ticker", keepColumn: true);

            if (rootTickers.IsEmpty())
            {
                output = sortFrameByInput(output, tickers);
            }
            else
            {
                output = sortFrameByNaturalOrder(output, contractSortOrder);
            }

            StaticCache_.TryAdd(cacheKey, output.Clone());

            return output;

        }
Example #6
0
		/// <summary>
		/// Expansion Algorithm
		/// http://json-ld.org/spec/latest/json-ld-api/#expansion-algorithm
		/// </summary>
		/// <param name="activeCtx"></param>
		/// <param name="activeProperty"></param>
		/// <param name="element"></param>
		/// <returns></returns>
		/// <exception cref="JsonLdError">JsonLdError</exception>
		/// <exception cref="JsonLD.Core.JsonLdError"></exception>
		public virtual JToken Expand(Context activeCtx, string activeProperty, JToken element
			)
		{
			// 1)
			if (element.IsNull())
			{
				return null;
			}
			// 3)
			if (element is JArray)
			{
				// 3.1)
                JArray result = new JArray();
				// 3.2)
                foreach (JToken item in (JArray)element)
				{
					// 3.2.1)
					JToken v = Expand(activeCtx, activeProperty, item);
					// 3.2.2)
					if (("@list".Equals(activeProperty) || "@list".Equals(activeCtx.GetContainer(activeProperty
						))) && (v is JArray || (v is JObject && ((IDictionary<string, JToken>)v).ContainsKey
						("@list"))))
					{
						throw new JsonLdError(JsonLdError.Error.ListOfLists, "lists of lists are not permitted."
							);
					}
					else
					{
						// 3.2.3)
						if (!v.IsNull())
						{
							if (v is JArray)
							{
								JsonLD.Collections.AddAll(result, (JArray)v);
							}
							else
							{
								result.Add(v);
							}
						}
					}
				}
				// 3.3)
				return result;
			}
			else
			{
				// 4)
				if (element is JObject)
				{
					// access helper
                    IDictionary<string, JToken> elem = (JObject)element;
					// 5)
					if (elem.ContainsKey("@context"))
					{
						activeCtx = activeCtx.Parse(elem["@context"]);
					}
					// 6)
                    JObject result = new JObject();
					// 7)
                    JArray keys = new JArray(element.GetKeys());
					keys.SortInPlace();
					foreach (string key in keys)
					{
						JToken value = elem[key];
						// 7.1)
						if (key.Equals("@context"))
						{
							continue;
						}
						// 7.2)
						string expandedProperty = activeCtx.ExpandIri(key, false, true, null, null);
                        JToken expandedValue = null;
						// 7.3)
						if (expandedProperty == null || (!expandedProperty.Contains(":") && !JsonLdUtils.IsKeyword
							(expandedProperty)))
						{
							continue;
						}
						// 7.4)
						if (JsonLdUtils.IsKeyword(expandedProperty))
						{
							// 7.4.1)
							if ("@reverse".Equals(activeProperty))
							{
								throw new JsonLdError(JsonLdError.Error.InvalidReversePropertyMap, "a keyword cannot be used as a @reverse propery"
									);
							}
							// 7.4.2)
							if (result.ContainsKey(expandedProperty))
							{
								throw new JsonLdError(JsonLdError.Error.CollidingKeywords, expandedProperty + " already exists in result"
									);
							}
							// 7.4.3)
							if ("@id".Equals(expandedProperty))
							{
								if (!(value.Type == JTokenType.String))
								{
									throw new JsonLdError(JsonLdError.Error.InvalidIdValue, "value of @id must be a string"
										);
								}
								expandedValue = activeCtx.ExpandIri((string)value, true, false, null, null);
							}
							else
							{
								// 7.4.4)
								if ("@type".Equals(expandedProperty))
								{
                                    if (value is JArray)
									{
										expandedValue = new JArray();
										foreach (JToken v in (JArray)value)
										{
											if (v.Type != JTokenType.String)
											{
												throw new JsonLdError(JsonLdError.Error.InvalidTypeValue, "@type value must be a string or array of strings"
													);
											}
											((JArray)expandedValue).Add(activeCtx.ExpandIri((string)v, true, true, null
												, null));
										}
									}
									else
									{
										if (value.Type == JTokenType.String)
										{
											expandedValue = activeCtx.ExpandIri((string)value, true, true, null, null);
										}
										else
										{
											// TODO: SPEC: no mention of empty map check
											if (value is JObject)
											{
												if (((JObject)value).Count != 0)
												{
													throw new JsonLdError(JsonLdError.Error.InvalidTypeValue, "@type value must be a an empty object for framing"
														);
												}
												expandedValue = value;
											}
											else
											{
												throw new JsonLdError(JsonLdError.Error.InvalidTypeValue, "@type value must be a string or array of strings"
													);
											}
										}
									}
								}
								else
								{
									// 7.4.5)
									if ("@graph".Equals(expandedProperty))
									{
										expandedValue = Expand(activeCtx, "@graph", value);
									}
									else
									{
										// 7.4.6)
										if ("@value".Equals(expandedProperty))
										{
											if (!value.IsNull() && (value is JObject || value is JArray))
											{
												throw new JsonLdError(JsonLdError.Error.InvalidValueObjectValue, "value of " + expandedProperty
													 + " must be a scalar or null");
											}
											expandedValue = value;
											if (expandedValue.IsNull())
											{
												result["@value"] = null;
												continue;
											}
										}
										else
										{
											// 7.4.7)
											if ("@language".Equals(expandedProperty))
											{
												if (!(value.Type == JTokenType.String))
												{
													throw new JsonLdError(JsonLdError.Error.InvalidLanguageTaggedString, "Value of " 
														+ expandedProperty + " must be a string");
												}
												expandedValue = ((string)value).ToLower();
											}
											else
											{
												// 7.4.8)
												if ("@index".Equals(expandedProperty))
												{
													if (!(value.Type == JTokenType.String))
													{
														throw new JsonLdError(JsonLdError.Error.InvalidIndexValue, "Value of " + expandedProperty
															 + " must be a string");
													}
													expandedValue = value;
												}
												else
												{
													// 7.4.9)
													if ("@list".Equals(expandedProperty))
													{
														// 7.4.9.1)
														if (activeProperty == null || "@graph".Equals(activeProperty))
														{
															continue;
														}
														// 7.4.9.2)
														expandedValue = Expand(activeCtx, activeProperty, value);
														// NOTE: step not in the spec yet
                                                        if (!(expandedValue is JArray))
														{
                                                            JArray tmp = new JArray();
															tmp.Add(expandedValue);
															expandedValue = tmp;
														}
														// 7.4.9.3)
                                                        foreach (JToken o in (JArray)expandedValue)
														{
                                                            if (o is JObject && ((JObject)o).ContainsKey("@list"))
															{
																throw new JsonLdError(JsonLdError.Error.ListOfLists, "A list may not contain another list"
																	);
															}
														}
													}
													else
													{
														// 7.4.10)
														if ("@set".Equals(expandedProperty))
														{
															expandedValue = Expand(activeCtx, activeProperty, value);
														}
														else
														{
															// 7.4.11)
															if ("@reverse".Equals(expandedProperty))
															{
																if (!(value is JObject))
																{
																	throw new JsonLdError(JsonLdError.Error.InvalidReverseValue, "@reverse value must be an object"
																		);
																}
																// 7.4.11.1)
																expandedValue = Expand(activeCtx, "@reverse", value);
																// NOTE: algorithm assumes the result is a map
																// 7.4.11.2)
                                                                if (((IDictionary<string, JToken>)expandedValue).ContainsKey("@reverse"))
																{
                                                                    JObject reverse = (JObject)((JObject)expandedValue)["@reverse"];
																	foreach (string property in reverse.GetKeys())
																	{
                                                                        JToken item = reverse[property];
																		// 7.4.11.2.1)
																		if (!result.ContainsKey(property))
																		{
																			result[property] = new JArray();
																		}
																		// 7.4.11.2.2)
																		if (item is JArray)
																		{
                                                                            JsonLD.Collections.AddAll(((JArray)result[property]), (JArray)item);
																		}
																		else
																		{
                                                                            ((JArray)result[property]).Add(item);
																		}
																	}
																}
																// 7.4.11.3)
                                                                if (((JObject)expandedValue).Count > (((JObject)expandedValue).ContainsKey("@reverse") ? 1 : 0))
																{
																	// 7.4.11.3.1)
																	if (!result.ContainsKey("@reverse"))
																	{
                                                                        result["@reverse"] = new JObject();
																	}
																	// 7.4.11.3.2)
                                                                    JObject reverseMap = (JObject)result["@reverse"];
																	// 7.4.11.3.3)
                                                                    foreach (string property in expandedValue.GetKeys())
																	{
																		if ("@reverse".Equals(property))
																		{
																			continue;
																		}
																		// 7.4.11.3.3.1)
                                                                        JArray items = (JArray)((JObject)expandedValue)[property];
																		foreach (JToken item in items)
																		{
																			// 7.4.11.3.3.1.1)
                                                                            if (item is JObject && (((JObject)item).ContainsKey("@value") || ((JObject)item).ContainsKey("@list")))
																			{
																				throw new JsonLdError(JsonLdError.Error.InvalidReversePropertyValue);
																			}
																			// 7.4.11.3.3.1.2)
																			if (!reverseMap.ContainsKey(property))
																			{
																				reverseMap[property] = new JArray();
																			}
																			// 7.4.11.3.3.1.3)
                                                                            ((JArray)reverseMap[property]).Add(item);
																		}
																	}
																}
																// 7.4.11.4)
																continue;
															}
															else
															{
																// TODO: SPEC no mention of @explicit etc in spec
																if ("@explicit".Equals(expandedProperty) || "@default".Equals(expandedProperty) ||
																	 "@embed".Equals(expandedProperty) || "@embedChildren".Equals(expandedProperty) 
																	|| "@omitDefault".Equals(expandedProperty))
																{
																	expandedValue = Expand(activeCtx, expandedProperty, value);
																}
															}
														}
													}
												}
											}
										}
									}
								}
							}
							// 7.4.12)
							if (!expandedValue.IsNull())
							{
								result[expandedProperty] = expandedValue;
							}
							// 7.4.13)
							continue;
						}
						else
						{
							// 7.5
							if ("@language".Equals(activeCtx.GetContainer(key)) && value is JObject)
							{
								// 7.5.1)
                                expandedValue = new JArray();
								// 7.5.2)
								foreach (string language in value.GetKeys())
								{
                                    JToken languageValue = ((IDictionary<string, JToken>)value)[language];
									// 7.5.2.1)
									if (!(languageValue is JArray))
									{
                                        JToken tmp = languageValue;
                                        languageValue = new JArray();
                                        ((JArray)languageValue).Add(tmp);
									}
									// 7.5.2.2)
                                    foreach (JToken item in (JArray)languageValue)
									{
										// 7.5.2.2.1)
										if (!(item.Type == JTokenType.String))
										{
											throw new JsonLdError(JsonLdError.Error.InvalidLanguageMapValue, "Expected " + item
												.ToString() + " to be a string");
										}
										// 7.5.2.2.2)
                                        JObject tmp = new JObject();
										tmp["@value"] = item;
										tmp["@language"] = language.ToLower();
										((JArray)expandedValue).Add(tmp);
									}
								}
							}
							else
							{
								// 7.6)
								if ("@index".Equals(activeCtx.GetContainer(key)) && value is JObject)
								{
									// 7.6.1)
									expandedValue = new JArray();
									// 7.6.2)
                                    JArray indexKeys = new JArray(value.GetKeys());
									indexKeys.SortInPlace();
									foreach (string index in indexKeys)
									{
										JToken indexValue = ((JObject)value)[index];
										// 7.6.2.1)
										if (!(indexValue is JArray))
										{
											JToken tmp = indexValue;
											indexValue = new JArray();
											((JArray)indexValue).Add(tmp);
										}
										// 7.6.2.2)
										indexValue = Expand(activeCtx, key, indexValue);
										// 7.6.2.3)
										foreach (JObject item in (JArray)indexValue)
										{
											// 7.6.2.3.1)
											if (!item.ContainsKey("@index"))
											{
												item["@index"] = index;
											}
											// 7.6.2.3.2)
											((JArray)expandedValue).Add(item);
										}
									}
								}
								else
								{
									// 7.7)
									expandedValue = Expand(activeCtx, key, value);
								}
							}
						}
						// 7.8)
						if (expandedValue.IsNull())
						{
							continue;
						}
						// 7.9)
						if ("@list".Equals(activeCtx.GetContainer(key)))
						{
							if (!(expandedValue is JObject) || !((JObject)expandedValue).ContainsKey("@list"))
							{
								JToken tmp = expandedValue;
								if (!(tmp is JArray))
								{
									tmp = new JArray();
									((JArray)tmp).Add(expandedValue);
								}
								expandedValue = new JObject();
								((JObject)expandedValue)["@list"] = tmp;
							}
						}
						// 7.10)
						if (activeCtx.IsReverseProperty(key))
						{
							// 7.10.1)
							if (!result.ContainsKey("@reverse"))
							{
								result["@reverse"] = new JObject();
							}
							// 7.10.2)
							JObject reverseMap = (JObject)result["@reverse"];
							// 7.10.3)
                            if (!(expandedValue is JArray))
							{
                                JToken tmp = expandedValue;
								expandedValue = new JArray();
								((JArray)expandedValue).Add(tmp);
							}
							// 7.10.4)
							foreach (JToken item in (JArray)expandedValue)
							{
								// 7.10.4.1)
								if (item is JObject && (((JObject)item).ContainsKey("@value") || ((JObject)item).ContainsKey("@list")))
								{
									throw new JsonLdError(JsonLdError.Error.InvalidReversePropertyValue);
								}
								// 7.10.4.2)
								if (!reverseMap.ContainsKey(expandedProperty))
								{
									reverseMap[expandedProperty] = new JArray();
								}
								// 7.10.4.3)
                                if (item is JArray)
								{
                                    JsonLD.Collections.AddAll(((JArray)reverseMap[expandedProperty]), (JArray)item);
								}
								else
								{
									((JArray)reverseMap[expandedProperty]).Add(item);
								}
							}
						}
						else
						{
							// 7.11)
							// 7.11.1)
							if (!result.ContainsKey(expandedProperty))
							{
								result[expandedProperty] = new JArray();
							}
							// 7.11.2)
                            if (expandedValue is JArray)
							{
                                JsonLD.Collections.AddAll(((JArray)result[expandedProperty]), (JArray)expandedValue);
							}
							else
							{
								((JArray)result[expandedProperty]).Add(expandedValue);
							}
						}
					}
					// 8)
					if (result.ContainsKey("@value"))
					{
						// 8.1)
						// TODO: is this method faster than just using containsKey for
						// each?
						ICollection<string> keySet = new HashSet<string>(result.GetKeys());
						keySet.Remove("@value");
						keySet.Remove("@index");
						bool langremoved = keySet.Remove("@language");
						bool typeremoved = keySet.Remove("@type");
						if ((langremoved && typeremoved) || !keySet.IsEmpty())
						{
							throw new JsonLdError(JsonLdError.Error.InvalidValueObject, "value object has unknown keys"
								);
						}
						// 8.2)
                        JToken rval = result["@value"];
						if (rval.IsNull())
						{
							// nothing else is possible with result if we set it to
							// null, so simply return it
							return null;
						}
						// 8.3)
						if (!(rval.Type == JTokenType.String) && result.ContainsKey("@language"))
						{
							throw new JsonLdError(JsonLdError.Error.InvalidLanguageTaggedValue, "when @language is used, @value must be a string"
								);
						}
						else
						{
							// 8.4)
							if (result.ContainsKey("@type"))
							{
								// TODO: is this enough for "is an IRI"
								if (!(result["@type"].Type == JTokenType.String) || ((string)result["@type"]).StartsWith("_:") ||
									 !((string)result["@type"]).Contains(":"))
								{
									throw new JsonLdError(JsonLdError.Error.InvalidTypedValue, "value of @type must be an IRI"
										);
								}
							}
						}
					}
					else
					{
						// 9)
						if (result.ContainsKey("@type"))
						{
                            JToken rtype = result["@type"];
							if (!(rtype is JArray))
							{
								JArray tmp = new JArray();
								tmp.Add(rtype);
								result["@type"] = tmp;
							}
						}
						else
						{
							// 10)
							if (result.ContainsKey("@set") || result.ContainsKey("@list"))
							{
								// 10.1)
								if (result.Count > (result.ContainsKey("@index") ? 2 : 1))
								{
									throw new JsonLdError(JsonLdError.Error.InvalidSetOrListObject, "@set or @list may only contain @index"
										);
								}
								// 10.2)
								if (result.ContainsKey("@set"))
								{
									// result becomes an array here, thus the remaining checks
									// will never be true from here on
									// so simply return the value rather than have to make
									// result an object and cast it with every
									// other use in the function.
									return result["@set"];
								}
							}
						}
					}
					// 11)
					if (result.ContainsKey("@language") && result.Count == 1)
					{
						result = null;
					}
					// 12)
					if (activeProperty == null || "@graph".Equals(activeProperty))
					{
						// 12.1)
						if (result != null && (result.Count == 0 || result.ContainsKey("@value") || result
							.ContainsKey("@list")))
						{
							result = null;
						}
						else
						{
							// 12.2)
							if (result != null && result.ContainsKey("@id") && result.Count == 1)
							{
								result = null;
							}
						}
					}
					// 13)
					return result;
				}
				else
				{
					// 2) If element is a scalar
					// 2.1)
					if (activeProperty == null || "@graph".Equals(activeProperty))
					{
						return null;
					}
					return activeCtx.ExpandValue(activeProperty, element);
				}
			}
		}