private IList <PrefixExpressionContext> FindOriginalContexts([NotNull] PostfixTemplateContext context) { var results = new LocalList <PrefixExpressionContext>(); var images = new List <ExpressionContextImage>(myImages); for (var index = 0; index < images.Count; index++) // order is important { foreach (var expressionContext in context.ExpressionsOrTypes) { if (images[index].MatchesByRangeAndType(expressionContext)) { images[index] = null; results.Add(expressionContext); break; } } } if (results.Count == 0) { var expressions = context.Expressions; foreach (var image in myImages) { if (image != null && image.ContextIndex < expressions.Count) { results.Add(expressions[image.ContextIndex]); } } } return(results.ResultingList()); }
public void RemoveAtIfEmpty() { LocalList <int> list = default; Assert.AreEqual(0, list.Count); Assert.Throws <IndexOutOfRangeException>(() => { list.RemoveAt(0); }); }
private CflowTranslatorCtx TranslatorInit(bool fromFirstBlock) { ParameterList methodParameters = this.blocks.Method.Parameters; LocalList methodLocals = this.blocks.Method.Body.Variables; CflowTranslatorCtx translator = new CflowTranslatorCtx(ctx, new CflowStack(), new List <BitVecExpr>(), new List <BitVecExpr>()); for (int i = 0; i < methodParameters.Count; i++) { translator.Args.Add(ctx.MkBVConst("Arg" + i.ToString(), 32)); } for (int i = 0; i < methodLocals.Count; i++) { if (fromFirstBlock) { translator.Locals.Add(ctx.MkBV(0, 32)); } else { translator.Locals.Add(ctx.MkBVConst("Loc" + i.ToString(), 32)); } } return(translator); }
public override LocalList <IDeclaredElement> GetBanMarksFromNode(ITreeNode currentNode, IDeclaredElement containingFunction) { var result = new LocalList <IDeclaredElement>(); if (containingFunction == null) { return(result); } var functionDeclaration = currentNode as IFunctionDeclaration; var function = functionDeclaration?.DeclaredElement; if (function == null) { return(result); } if (IsBurstProhibitedFunction(function) || CheckBurstBannedAnalyzers(functionDeclaration)) { result.Add(function); } return(result); }
public override LocalList <IDeclaredElement> GetRootMarksFromNode(ITreeNode currentNode, IDeclaredElement containingFunction) { var result = new LocalList <IDeclaredElement>(); var coroutineOrInvoke = ExtractCoroutineOrInvokeRepeating(currentNode); if (coroutineOrInvoke != null) { result.Add(coroutineOrInvoke); } if (containingFunction == null) { return(result); } var declaration = currentNode as IDeclaration; var declaredElement = declaration?.DeclaredElement; if (!ReferenceEquals(containingFunction, declaredElement)) { return(result); } var processor = new PerformanceCriticalCodeProcessor(); declaration.ProcessThisAndDescendants(processor); if (processor.IsPerformanceCriticalCodeFound) { result.Add(declaredElement); } return(result); }
public ArrayRenderer GetArrayRenderer(string template, object[] args) { if (_renderers.TryGetValue(template, out var renderer)) { return((ArrayRenderer)renderer); } var arguments = BuildArguments(template); var argumentTypes = new LocalList <Type>(args.Length); foreach (var arg in args) { argumentTypes.Add(arg.GetType()); } var messageRenderer = new DefaultStringFormatter(template); renderer = new ArrayRenderer(arguments, messageRenderer, argumentTypes, _converters); using (Lock.Enter(_lock)) { _renderers[template] = renderer; } return((ArrayRenderer)renderer); }
private static string[] BuildArguments(string template) { var argumentStarted = false; var arguments = new LocalList <string>(); var builder = new LocalList <char>(); foreach (var ch in template) { switch (ch) { case '{': argumentStarted = true; break; case '}': arguments.Add(new string(builder.ToArray())); builder.Clear(); argumentStarted = false; break; default: if (argumentStarted) { builder.Add(ch); } break; } } return(arguments.ToArray()); }
private LocalList <IProjectToUnresolvedAssemblyReference> GetUnresolvedReferences(ProjectModelChange projectModelChange) { var result = new LocalList <IProjectToUnresolvedAssemblyReference>(); var q = new Queue <ProjectModelChange>(); q.Enqueue(projectModelChange); while (q.Count > 0) { var change = q.Dequeue(); if (change == null) { continue; } var reference = change.ProjectModelElement as IProjectToUnresolvedAssemblyReference; if (reference != null && ProjectExtensions.UnityReferenceNames.Contains(reference.ReferenceTarget.AssemblyName) && change.IsAdded) { result.Add(reference); } foreach (var c in change.GetChildren()) { q.Enqueue(c); } } return(result); }
public async Task <IActionResult> Create() { var enumexcel = EnumerateExcel(); LocalList ll = new LocalList(); foreach (var e in enumexcel) { ll.LocalWagonList.Add(new ParserModel() { TCNumber = e.TCNumber, WaybillNumber = e.WaybillNumber }); } for (int i = 0; i < ll.LocalWagonList.Count; i++) { var wagon = new ParserModel() { TCNumber = ll.LocalWagonList[i].TCNumber, WaybillNumber = ll.LocalWagonList[i].WaybillNumber }; db.Wagons.Add(wagon); } await db.SaveChangesAsync(); return(RedirectToAction("Index")); }
// ReSharper disable once ReturnTypeCanBeEnumerable.Global public static Assembly[] GetUserAssemblies() { var assemblies = AppDomain.CurrentDomain.GetAssemblies(); var result = new LocalList <Assembly>(); foreach (var assembly in assemblies) { if (assembly.IsDynamic) { continue; } var name = assembly.FullName; if (name.StartsWith("Microsoft") || name.StartsWith("System") || name.StartsWith("NuGet") || name.StartsWith("netstandard") || name.StartsWith("mscorlib") || name.StartsWith("xunit") || name.StartsWith("Newtonsoft") || name.StartsWith("JetBrains") || name.StartsWith("Castle") || name.StartsWith("Moq") || name.StartsWith("AutoFixture") || name.StartsWith("FluentAssertions") || name == "Velo") { continue; } result.Add(assembly); } return(result.ToArray()); }
protected override IDeclaredElement CreateDeclaredElement() { // the field doesn't have a name and is in a union case or in an exception var typeDeclaration = Parent as IFSharpTypeDeclaration; var typeSymbol = typeDeclaration?.GetFSharpSymbol(); if (typeSymbol == null) { return(null); } var result = new LocalList <IUnionCaseFieldDeclaration>(); foreach (var child in typeDeclaration.Children()) { if (child is IUnionCaseFieldDeclaration fieldDeclaration) { result.Add(fieldDeclaration); } } var fieldDeclarations = result.ReadOnlyList(); var index = fieldDeclarations.IndexOf(this); var fields = GetFields(typeSymbol); var caseField = fields != null && index <= fields.Count ? fields[index] : null; return(caseField != null ? new FSharpUnionCaseField(this, caseField) : null); }
private void OnUnityProjectAdded(IProject project) { if (!myProjectLifetimes.TryGetValue(project, out var projectLifetime)) { return; } if (!HasUnityReference.Value) { HasUnityReference.SetValue(true); } var exceptions = new LocalList <Exception>(); foreach (var handler in myHandlers) { try { handler.OnUnityProjectAdded(projectLifetime, project); } catch (Exception e) { exceptions.Add(e); } } if (exceptions.Count > 0) { throw new AggregateException("Failed to handle project changes", exceptions.ToArray()); } }
private void LocalItem_MouseMove(object sender, MouseEventArgs e) { if ((e.LeftButton != MouseButtonState.Pressed) || (LocalList.SelectedItems.Count == 0)) { return; } SmartItem[] Items = LocalList.SelectedItems(); if (Items == null) { return; } if (Items[0].FullName == LocalHelper.ThisPC) { return; } string[] items = new string[Items.Length]; for (int i = 0; i < Items.Length; i++) { items[i] = Items[i].FullName; } Items = null; draggingFrom = DraggingFrom.LocalList; DragDrop.DoDragDrop(this, new DataObject(DataFormats.FileDrop, items), DragDropEffects.Copy); }
public object?ReadValue(JsonObject source) { if (!source.TryGet(nameof(IEntity.Components), out var componentsData)) { return(null); } var components = new LocalList <IComponent>(); foreach (var(name, data) in (JsonObject)componentsData) { var componentType = _descriptions.GetComponentType(name); var component = _componentFactory.Create(componentType); var componentConverter = (IObjectConverter)_converters.Get(componentType); var filledComponent = componentConverter.FillObject((JsonObject)data, component); if (filledComponent != null) { components.Add((IComponent)filledComponent); } } return(components.ToArray()); }
public override LocalList <IDeclaredElement> GetRootMarksFromNode(ITreeNode currentNode, IDeclaredElement containingFunction) { var result = new LocalList <IDeclaredElement>(); var coroutineOrInvoke = ExtractCoroutineOrInvokeRepeating(currentNode); if (coroutineOrInvoke != null) { result.Add(coroutineOrInvoke); } // it means we are in functional type member like methodDeclaration if (containingFunction == null) { return(result); } var functionDeclaration = currentNode as IFunctionDeclaration; var hasComment = UnityCallGraphUtil.HasAnalysisComment(functionDeclaration, MarkId, ReSharperControlConstruct.Kind.Restore); if (hasComment) { result.Add(functionDeclaration.DeclaredElement); } var declaration = currentNode as ITypeMemberDeclaration; var typeMember = declaration?.DeclaredElement; if (PerformanceCriticalCodeStageUtil.IsPerformanceCriticalRootMethod(typeMember)) { result.Add(typeMember); } return(result); }
public static DependencyLifetime DefineLifetime(this IDependencyEngine engine, Type implementation) { var constructor = ReflectionUtils.GetConstructor(implementation); if (constructor == null) { throw Error.DefaultConstructorNotFound(implementation); } var parameters = constructor.GetParameters(); var dependencies = new LocalList <DependencyLifetime>(); foreach (var parameter in parameters) { var required = !parameter.HasDefaultValue; var dependency = required ? engine.GetRequiredDependency(parameter.ParameterType) : engine.GetDependency(parameter.ParameterType); if (dependency != null) { dependencies.Add(dependency.Lifetime); } } return(dependencies.DefineLifetime()); }
public static DependencyLifetime DefineLifetime(this LocalList <DependencyLifetime> lifetimes) { int singleton = 0, transient = 0; foreach (var lifetime in lifetimes) { switch (lifetime) { case DependencyLifetime.Singleton: singleton++; break; case DependencyLifetime.Transient: transient++; break; } } if (singleton == lifetimes.Length) { return(DependencyLifetime.Singleton); } return(transient == 0 ? DependencyLifetime.Scoped : DependencyLifetime.Transient); }
private IList <LookupItem <PostfixTemplateInfo> > BuildLookupItems([NotNull] TPostfixTemplateContext context, [NotNull] CodeCompletionContext completionContext) { var items = new LocalList <LookupItem <PostfixTemplateInfo> >(); //var multiplier = completionContext.Parameters.CodeCompletionTypes.Length; foreach (var templateRegistration in myTemplatesManager.GetEnabledTemplates(context)) { var templateProvider = templateRegistration.Template; var postfixTemplateInfo = templateProvider.TryCreateInfo(context); if (postfixTemplateInfo == null) { continue; } var templateName = templateRegistration.Metadata.TemplateName; Assertion.Assert( string.Equals(templateName, postfixTemplateInfo.Text, StringComparison.Ordinal), "Template text '{0}' should match declared template name '{1}'", postfixTemplateInfo.Text, templateName); //postfixTemplateInfo.Multiplier = multiplier; items.Add(LookupItemFactory.CreateLookupItem(postfixTemplateInfo) .WithMatcher(item => new PostfixTemplateMatcher(item.Info)) .WithBehavior(item => templateProvider.CreateBehavior(item.Info)) .WithPresentation(item => new PostfixTemplatePresentation(item.Info.Text))); } return(items.ResultingList()); }
private void Handle(IProject project) { Lifetime projectLifetime; if (!myProjectLifetimes.TryGetValue(project, out projectLifetime)) { return; } var exceptions = new LocalList <Exception>(); foreach (var handler in myHandlers) { try { handler.OnReferenceAdded(project, projectLifetime); if (project.IsUnityProject()) { myIsUnityProject.SetValue(true, myToken); } } catch (Exception e) { exceptions.Add(e); } } if (exceptions.Count > 0) { throw new AggregateException("Failed to handle project changes", exceptions.ToArray()); } }
public static LocalList <Type> GetGenericInterfaceImplementations(Type type, Type genericInterface, bool throwIfNotFound = true) { CheckIsGenericInterfaceTypeDefinition(genericInterface); var implementations = new LocalList <Type>(); if (type.IsInterface && IsGenericTypeImplementation(type, genericInterface)) { implementations.Add(type); } var interfaces = type.GetInterfaces(); foreach (var typeInterface in interfaces) { if (IsGenericTypeImplementation(typeInterface, genericInterface)) { implementations.Add(typeInterface); } } if (throwIfNotFound && implementations.Length == 0) { throw Error.NotFound($"Generic interface {GetName(genericInterface)} is not implemented"); } return(implementations); }
protected override void Merge(ILambdaExpression accumulatorLambda, ILambdaExpression lambda) { var declaredElement = lambda.ParameterDeclarations[0].DeclaredElement; var replacement = accumulatorLambda.BodyExpression; var toReplace = new LocalList <IReferenceExpression>(); foreach (var referenceExpression in lambda.BodyExpression.Descendants <IReferenceExpression>()) { var currentElement = referenceExpression.Reference.Resolve().DeclaredElement; if (declaredElement.Equals(currentElement) || referenceExpression.QualifierExpression == null && referenceExpression.NameIdentifier.Name == declaredElement.ShortName) { toReplace.Add(referenceExpression); } } for (int i = 0; i < toReplace.Count; i++) { toReplace[i].ReplaceBy(replacement); } accumulatorLambda.SetBodyExpression(lambda.BodyExpression); }
public void RemoveIfEmpty() { LocalList <int> list = default; Assert.AreEqual(0, list.Count); Assert.AreEqual(false, list.Remove(29)); }
void SearchFinished(SearchEngine sList) { lock ("ItemLists") { foreach (ItemPriceList list in sList.SearchItemL) { if (LocalList.ContainsKey(list.ItemName)) { List <ItemVend> ToAdd = new List <ItemVend>(); foreach (ItemVend item in list.ItemPriceL) { if (!LocalList[list.ItemName].ItemPriceL.Contains(item)) { ToAdd.Add(item); } } foreach (ItemVend item in ToAdd) { LocalList[list.ItemName].ItemPriceL.Add(item); } } else { LocalList.Add(list.ItemName, list); } } } if (Text != OldText) { OldText = Text; Commit(); ShowWindow(); } }
protected override void Merge(ILambdaExpression accumulatorLambda, ILambdaExpression lambda) { var declaredElement = lambda.ParameterDeclarations[0].DeclaredElement; var replacement = accumulatorLambda.BodyExpression; var toReplace = new LocalList<IReferenceExpression>(); foreach (var referenceExpression in lambda.BodyExpression.Descendants<IReferenceExpression>()) { var currentElement = referenceExpression.Reference.Resolve().DeclaredElement; if (declaredElement.Equals(currentElement) || referenceExpression.QualifierExpression == null && referenceExpression.NameIdentifier.Name == declaredElement.ShortName) { toReplace.Add(referenceExpression); } } for (int i = 0; i < toReplace.Count; i++) { toReplace[i].ReplaceBy(replacement); } accumulatorLambda.SetBodyExpression(lambda.BodyExpression); }
public DefaultStringFormatter(string template) { var parts = new LocalList <Part>(); var buffer = new StringBuilder(); foreach (var ch in template) { switch (ch) { case '{': if (buffer.Length > 0) { parts.Add(BuildPart(buffer, false)); } break; case '}': parts.Add(BuildPart(buffer, true)); break; default: buffer.Append(ch); break; } } if (buffer.Length > 0) { parts.Add(BuildPart(buffer, false)); } _parts = parts.ToArray(); }
void SearchStarted(SearchEngine sList) { lock ("ItemLists") { foreach (ItemPriceList list in sList.LocalSearchItemL) { if (LocalList.ContainsKey(list.ItemName)) { List <ItemVend> ToRemove = new List <ItemVend>(); foreach (ItemVend item in list.ItemPriceL) { if (LocalList[list.ItemName].ItemPriceL.Contains(item)) { ToRemove.Add(item); } } foreach (ItemVend item in ToRemove) { LocalList[list.ItemName].ItemPriceL.Remove(item); } if (LocalList[list.ItemName].ItemPriceL.Count == 0) { LocalList.Remove(list.ItemName); } } } } }
public string[]? ReadAnsiStringsPlus ( int count ) { // Sure.Positive(count, nameof(count)); var result = new LocalList <string>(count); int index = 0; string line; for (; index < 1; index++) { line = ReadAnsi(); if (string.IsNullOrEmpty(line)) { return(null); } result.Add(line); } for (; index < count; index++) { line = ReadAnsi(); result.Add(line); } return(result.ToArray()); }
private static void TryAdd(ref LocalList <Type> contracts, Type contract, Type implementation) { if (implementation.IsAssignableFrom(contract)) { contracts.Add(contract); } }
private static IEnumerable <ExceptionContent> GetExceptions([NotNull] IDeclaredElement element, [NotNull] PsiLanguageType languageType, [NotNull] IPsiModule psiModule, [NotNull] IModuleReferenceResolveContext resolveContext) { XmlNode xmlDoc = element.GetXMLDoc(true); if (xmlDoc == null) { return(EmptyList <ExceptionContent> .InstanceList); } XmlNodeList exceptionNodes = xmlDoc.SelectNodes("exception"); if (exceptionNodes == null || exceptionNodes.Count == 0) { return(EmptyList <ExceptionContent> .InstanceList); } var exceptions = new LocalList <ExceptionContent>(); foreach (XmlNode exceptionNode in exceptionNodes) { ExceptionContent exceptionContent = TryExtractException(exceptionNode as XmlElement, languageType, psiModule, resolveContext); if (exceptionContent != null) { exceptions.Add(exceptionContent); } } return(exceptions.ResultingList()); }
public override LocalList <IDeclaredElement> GetMarkedFunctionsFrom(ITreeNode currentNode, IDeclaredElement containingFunction) { var result = new LocalList <IDeclaredElement>(); if (currentNode is IMethodDeclaration methodDeclaration) { if (PerformanceCriticalCodeStageUtil.HasFrequentlyCalledMethodAttribute(methodDeclaration)) { result.Add(containingFunction); } else if (ourKnownHotMonoBehaviourMethods.Contains(methodDeclaration.DeclaredName)) { var containingTypeDeclaration = methodDeclaration.GetContainingTypeDeclaration()?.DeclaredElement; if (myUnityApi.IsDescendantOfMonoBehaviour(containingTypeDeclaration)) { result.Add(containingFunction); } } } var coroutineOrInvoke = ExtractCoroutineOrInvokeRepeating(currentNode); if (coroutineOrInvoke != null) { result.Add(coroutineOrInvoke); } return(result); }
private void Handle(IProject project) { Lifetime projectLifetime; if (!myProjectLifetimes.TryGetValue(project, out projectLifetime)) { return; } var exceptions = new LocalList <Exception>(); foreach (var handler in myHandlers) { try { handler(projectLifetime, project); } catch (Exception e) { exceptions.Add(e); } } if (exceptions.Count > 0) { throw new AggregateException("Failed to handle project changes", exceptions.ToArray()); } }
public static void EnsureFirstSuggestionIsUnique( [NotNull] IList<string> suggestions, ref LocalList<IList<string>> previousSuggestions) { if (previousSuggestions.Count == 0) return; int uniqueIndex = FindIndexOfFirstUniqueSuggestion(suggestions, ref previousSuggestions); if (uniqueIndex == 0) return; if (uniqueIndex > 0) { suggestions.Swap(0, uniqueIndex); return; } MakeFirstSuggestionUniqueWithNumericSuffix(suggestions, ref previousSuggestions); }
protected override Action<ITextControl> ExecutePsiTransaction(ISolution solution, IProgressIndicator progress) { var invocation = myChainedInvocation.NotNull(); invocation = ((IInvocationExpression) StatementUtil.EnsureStatementExpression(invocation)).NotNull(); var declarations = new LocalList<IDeclarationStatement>(myInvocationsCount - 1); var variableNameSuggestions = new LocalList<IList<string>>(myInvocationsCount - 1); SplitInvocation(invocation, ref declarations, ref variableNameSuggestions); InsertDeclarations(invocation, ref declarations); var hotspots = CreateHotspots(invocation, ref declarations, ref variableNameSuggestions); var invocationLine = DocumentHelper.GetNodeEndLine(invocation, myProvider.Document); Action<ITextControl> onFinish = textControl => textControl.MoveCaretToEndOfLine(invocationLine); return HotspotHelper.ExecuteHotspotSession(solution, hotspots, onFinish); }
public ILookupItem CreateItem(PostfixTemplateContext context) { var booleanExpressions = new LocalList<PrefixExpressionContext>(); var booleanType = context.Reference.GetPredefinedType().Bool; if (booleanType.IsResolved) { var conversionRule = context.Reference.GetTypeConversionRule(); foreach (var expressionContext in context.Expressions) { var expressionType = expressionContext.ExpressionType; if (expressionType.IsResolved) { if (!expressionType.IsImplicitlyConvertibleTo(booleanType, conversionRule) && !IsBooleanExpressionEx(expressionContext.Expression)) continue; } else { if (!IsBooleanExpressionEx(expressionContext.Expression)) continue; } booleanExpressions.Add(expressionContext); } } if (!context.IsAutoCompletion && booleanExpressions.Count == 0) { booleanExpressions.AddRange(context.Expressions); } if (booleanExpressions.Count > 0) { return CreateBooleanItem(booleanExpressions.ToArray()); } return null; }
private HotspotInfo CreateHostHotspotInfo() { var lambda = (ILambdaExpression)myOuterInvocation.NotNull().Arguments[0].Value; var lambdaParameter = lambda.ParameterDeclarations[0]; var name = lambdaParameter.DeclaredName; var templateField = new TemplateField(name, new MacroCallExpressionNew(new SuggestVariableNameMacroDef()), 0); var documentRange = lambdaParameter.GetNameDocumentRange(); var documentRanges = new LocalList<DocumentRange>(); documentRanges.Add(documentRange); CollectUsageRanges(lambdaParameter.DeclaredElement, lambda.BodyExpression, ref documentRanges); return new HotspotInfo(templateField, documentRanges.ToArray()); }
private void SplitInvocation( [NotNull] IInvocationExpression invocation, ref LocalList<IDeclarationStatement> declarations, ref LocalList<IList<string>> variableNameSuggestions) { var innerInvocation = invocation.GetInnerInvocation(); if (innerInvocation == null) return; var returnType = innerInvocation.Type(); SplitInvocation(innerInvocation, ref declarations, ref variableNameSuggestions); var identifier = AddDeclaration(innerInvocation, returnType, ref declarations, ref variableNameSuggestions); SetInvocationTarget(invocation, identifier); }
private static void InsertDeclarations( [NotNull] IInvocationExpression invocation, ref LocalList<IDeclarationStatement> declarations) { IBlock block = invocation.GetContainingNode<IBlock>(true).NotNull(); ICSharpStatement anchor = invocation.GetContainingStatement(); for (var i = declarations.Count - 1; i >= 0; i--) { declarations[i] = block.AddStatementBefore(declarations[i], anchor); anchor = declarations[i]; } }
private static HotspotInfo[] CreateHotspots( [NotNull] IInvocationExpression invocation, ref LocalList<IDeclarationStatement> declarations, ref LocalList<IList<string>> variableNameSuggestions) { bool isTypeInferenceSupported = invocation.IsCSharp3Supported(); if (isTypeInferenceSupported) { var hotspots = new HotspotInfo[declarations.Count * 2]; for (int i = 0; i < declarations.Count - 1; i++) { hotspots[2 * i] = CreateVariableTypeHotspot(declarations[i]); hotspots[2 * i + 1] = CreateVariableNameHotspot(declarations[i], declarations[i + 1], variableNameSuggestions[i]); } var lastDeclaration = declarations[declarations.Count - 1]; var lastSuggestions = variableNameSuggestions[variableNameSuggestions.Count - 1]; hotspots[hotspots.Length - 2] = CreateVariableTypeHotspot(lastDeclaration); hotspots[hotspots.Length - 1] = CreateVariableNameHotspot(lastDeclaration, invocation, lastSuggestions); return hotspots; } else { var hotspots = new HotspotInfo[declarations.Count]; for (int i = 0; i < hotspots.Length - 1; i++) { hotspots[i] = CreateVariableNameHotspot(declarations[i], declarations[i + 1], variableNameSuggestions[i]); } var lastDeclaration = declarations[declarations.Count - 1]; var lastSuggestions = variableNameSuggestions[variableNameSuggestions.Count - 1]; hotspots[hotspots.Length - 1] = CreateVariableNameHotspot(lastDeclaration, invocation, lastSuggestions); return hotspots; } }
private static IList<ITypeMember> GetStaticColorProperties(ITypeElement unityColorType) { var colorProperties = new LocalList<ITypeMember>(); foreach (var typeMember in unityColorType.GetMembers()) { if (!typeMember.IsStatic) continue; var typeOwner = typeMember as ITypeOwner; if (typeOwner is IProperty || typeOwner is IField) { var declaredType = typeOwner.Type as IDeclaredType; if (declaredType != null && unityColorType.Equals(declaredType.GetTypeElement())) { colorProperties.Add(typeMember); } } } return colorProperties.ResultingList(); }
private string AddDeclaration( [NotNull] IInvocationExpression invocation, [NotNull] IType variableType, ref LocalList<IDeclarationStatement> declarations, ref LocalList<IList<string>> variableNameSuggestions) { var declaration = (IDeclarationStatement)myFactory.CreateStatement("$0 $1 = $2;", variableType, "__", invocation); var variable = declaration.VariableDeclarations[0]; var variableNames = NameHelper.SuggestVariableNames(invocation, variable.DeclaredElement, variableType); NameHelper.EnsureFirstSuggestionIsUnique(variableNames, ref variableNameSuggestions); variableNameSuggestions.Add(variableNames); variable.SetName(variableNames[0]); declarations.Add(declaration); return variableNames[0]; }
internal void GetLocals(int localIndex, LocalList/*!*/ locals, Hashtable/*!*/ localSourceNames) { if (localIndex == 0) return; StandAloneSigRow ssr = this.tables.StandAloneSigTable[(localIndex & 0xFFFFFF) - 1]; this.tables.GetSignatureLength(ssr.Signature); MemoryCursor sigReader = this.tables.GetNewCursor(); if (sigReader.ReadByte() != 0x7) throw new InvalidMetadataException(ExceptionStrings.InvalidLocalSignature); int count = sigReader.ReadCompressedInt(); for (int i = 0; i < count; i++) { string lookupName = (string)localSourceNames[i]; string name = lookupName == null ? "local" + i : lookupName; bool pinned = false; TypeNode locType = this.ParseTypeSignature(sigReader, ref pinned); Local loc = new Local(Identifier.For(name), locType); loc.Pinned = pinned; locals.Add(loc); } }
public override Method VisitMethod(Method method) { if (method == null) return null; if (method.IsNormalized) return method; if (method.CciKind != CciMemberKind.Regular) { method.Attributes.Add(new AttributeNode(new MemberBinding(null, SystemTypes.CciMemberKindAttribute.GetConstructor(SystemTypes.CciMemberKind)), new ExpressionList(new Literal(method.CciKind, SystemTypes.CciMemberKind)), AttributeTargets.Method)); } method.IsNormalized = true; method.Attributes = this.VisitAttributeList(method.Attributes); if (method.ReturnAttributes == null) method.ReturnAttributes = new AttributeList(); else method.ReturnAttributes = this.VisitAttributeList(method.ReturnAttributes); AttributeList al = this.ExtractAttributes(method.Attributes, AttributeTargets.ReturnValue); for (int i = 0, n = al == null ? 0 : al.Count; i < n; i++){ method.ReturnAttributes.Add(al[i]); } method.SecurityAttributes = this.VisitSecurityAttributeList(method.SecurityAttributes); if (method.Attributes != null && method.Attributes.Count > 0) { SecurityAttributeList secAttrs = method.SecurityAttributes; this.ExtractSecurityAttributes(method.Attributes, ref secAttrs); method.SecurityAttributes = secAttrs; } if (method.SecurityAttributes != null && method.SecurityAttributes.Count > 0) method.Flags |= MethodFlags.HasSecurity; Method savedMethod = this.currentMethod; This savedThisParameter = this.currentThisParameter; Local savedReturnLocal = this.currentReturnLocal; Block savedReturnLabel = this.currentReturnLabel; Local savedClosureLocal = this.currentClosureLocal; Block savedContractPrelude = this.currentContractPrelude; BlockList savedContractExceptionalTerminationChecks = this.currentContractExceptionalTerminationChecks; Local savedcurrentExceptionalTerminationException = this.currentExceptionalTerminationException; Block savedContractNormalTerminationCheck = this.currentContractNormalTerminationCheck; Block savedParentBlock = null; this.currentMethod = method; this.currentThisParameter = method.ThisParameter; if (method.ThisParameter != null) { method.ThisParameter.DeclaringMethod = method; if (method.DeclaringType != null && method.DeclaringType.IsValueType) method.ThisParameter.Type = method.DeclaringType.GetReferenceType(); } this.currentReturnLabel = new Block(new StatementList()); this.currentClosureLocal = null; this.currentContractPrelude = new Block(new StatementList()); this.currentContractExceptionalTerminationChecks = new BlockList(); this.currentExceptionalTerminationException = new Local(Identifier.For("SS$caught_exception"), SystemTypes.Exception); this.currentContractNormalTerminationCheck = new Block(new StatementList()); if (TypeNode.StripModifiers(method.ReturnType) == SystemTypes.Void) this.currentReturnLocal = null; else this.currentReturnLocal = new Local(Identifier.For("return value"), method.ReturnType); method.Parameters = this.VisitParameterList(method.Parameters); method.TemplateArguments = this.VisitTypeReferenceList(method.TemplateArguments); method.TemplateParameters = this.VisitTypeParameterList(method.TemplateParameters); TypeNodeList tpars = method.TemplateParameters; if (!method.IsGeneric){ for (int i = 0, n = tpars == null ? 0 : tpars.Count; i < n; i++){ TypeNode tpar = tpars[i]; if (tpar == null) continue; tpar.Name = new Identifier(method.Name+":"+tpar.Name, tpar.SourceContext); tpar.DeclaringType = method.DeclaringType; method.DeclaringType.Members.Add(tpar); } } if (method.Template == null) { // skip this part for instance methods. Block closureInit = null; bool methodHasClosure = method.Scope != null && method.Scope.CapturedForClosure; if (methodHasClosure) this.SetUpClosureClass(method); // Normalizer.VisitRequiresList needs to be called in case it wants to generate // some default preconditions (that are not injected by Checker in order to not // have these preconditions seen by any static checking tools). If there is // no contract on this method, then it won't get called, so create a dummy // contract and Requires list just so it will get a chance to do its stuff. if (method.Contract == null) { method.Contract = new MethodContract(method); method.Contract.Requires = new RequiresList(); } if (!methodHasClosure || (method is InstanceInitializer)) { // ctors will construct the closure class instance after they call another ctor, since they need to pass in "this" as a parameter to the closure class constructor method.Contract = this.VisitMethodContract(method.Contract); method.Body = this.VisitBlock(method.Body); }else{ method.Contract = this.VisitMethodContract(method.Contract); Block b = this.CreateClosureClassInstance(method); method.Body = this.VisitBlock(method.Body); savedParentBlock = method.Body; closureInit = b; if (method.Body != null){ closureInit.SourceContext = method.Body.SourceContext; method.Body.HasLocals = true; } } { #region If this method has a contract, then modify its body to add the contracts at the right point if (method.Body != null && method.Body.Statements != null){ if (this.currentContractExceptionalTerminationChecks.Count > 0){ // then wrap the body into a try catch with these checks as the catch blocks Block b = new Block(new StatementList(this.currentContractExceptionalTerminationChecks.Count)); b.HasLocals = true; for (int i = 0, n = this.currentContractExceptionalTerminationChecks.Count; i < n; i++) { b.Statements.Add(this.currentContractExceptionalTerminationChecks[i]); } #region Rethrow caught exception // last "functional" thing in the block is re-throw whatever exception we caught. Throw t = new Throw(); t.NodeType = NodeType.Rethrow; b.Statements.Add(t); #endregion LocalList ls = new LocalList(1); this.currentExceptionalTerminationException.DeclaringBlock = b; ls.Add(this.currentExceptionalTerminationException); BlockList bs = new BlockList(1); bs.Add(b); Block newBody = CreateTryCatchBlock(method, method.Body, bs, ls); //Block newBody = CreateTryCatchBlock(method,method.Body,this.currentContractExceptionalTerminationChecks,this.currentContractExceptionalLocals); method.Body = newBody; } if (this.currentContractPrelude.Statements.Count > 0){ Block newBody = new Block(new StatementList(3)); // Wrap the contract prelude in a block with a dummy catch block. // It has a special handler type that lets downstream tools know // this block was not part of the original code. Throw t = new Throw(); t.NodeType = NodeType.Rethrow; this.currentContractPrelude = CreateTryCatchBlock( method, this.currentContractPrelude, // try body new Block(new StatementList(t)), // catch: just rethrow new Local(Identifier.For("SS$Contract Marker"), SystemTypes.ContractMarkerException) ); newBody.Statements.Add(closureInit); closureInit = null; newBody.Statements.Add(this.currentContractPrelude); newBody.Statements.Add(method.Body); method.Body = newBody; } } } #endregion if (closureInit != null){ closureInit.Statements.Add(method.Body); method.Body = closureInit; } if (method.Body != null && method.Body.Statements != null){ Return r = new Return(); r.Expression = this.currentReturnLocal; Block returnBlock = new Block(new StatementList()); returnBlock.Statements.Add(this.currentReturnLabel); { InstanceInitializer ctor = method as InstanceInitializer; if (ctor != null && method.DeclaringType.Contract != null && method.DeclaringType.Contract.FrameField != null && !ctor.IsDeferringConstructor){ // then add a Pack to the end // BUGBUG: if the programmer has indicated that this default shouldn't apply, then don't do this! SourceContext rightBrace = new SourceContext(method.SourceContext.Document, method.SourceContext.EndPos - 1, method.SourceContext.EndPos); returnBlock.Statements.Add( new ExpressionStatement( new MethodCall(new MemberBinding(new MethodCall(new MemberBinding(method.ThisParameter, method.DeclaringType.Contract.FramePropertyGetter), null, NodeType.Call, OptionalModifier.For(SystemTypes.NonNullType, SystemTypes.Guard)), SystemTypes.Guard.GetMethod(Identifier.For("EndWriting"))), null, NodeType.Call, SystemTypes.Void), rightBrace )); } if (this.currentContractNormalTerminationCheck.Statements.Count > 0){ // Wrap the contract normal termination checks in a block with a dummy catch block. // It has a special handler type that lets downstream tools know this block was not // part of the original code. Throw t = new Throw(); t.NodeType = NodeType.Rethrow; this.currentContractNormalTerminationCheck = CreateTryCatchBlock( method, this.currentContractNormalTerminationCheck, // try body new Block(new StatementList(t)), // catch: just rethrow new Local(Identifier.For("SS$Contract Marker"),SystemTypes.ContractMarkerException) ); returnBlock.Statements.Add(this.currentContractNormalTerminationCheck); } } if (this.currentReturnLocal != null){ Local displayReturnLocal = new Local(Identifier.For("SS$Display Return Local"), method.ReturnType); returnBlock.Statements.Add(new AssignmentStatement(displayReturnLocal, this.currentReturnLocal)); returnBlock.HasLocals = true; } returnBlock.Statements.Add(r); if (method.Body.SourceContext.Document != null){ r.SourceContext = method.SourceContext; r.SourceContext.StartPos = method.Body.SourceContext.EndPos-1; } if (savedParentBlock != null){ if (savedParentBlock.Statements == null) savedParentBlock.Statements = new StatementList(1); savedParentBlock.Statements.Add(returnBlock); }else method.Body.Statements.Add(returnBlock); } if (method.ImplementedInterfaceMethods != null && method.ImplementedInterfaceMethods.Count > 0 && method.ImplementedInterfaceMethods[0] != null){ string typeName = method.ImplementedInterfaceMethods[0].DeclaringType.GetFullUnmangledNameWithTypeParameters(); method.Name = new Identifier(typeName + "." + method.Name.ToString(), method.Name.SourceContext); } if (method.HasCompilerGeneratedSignature && method.Parameters != null){ if (method.Parameters.Count == 1 && (method.Parameters[0].Attributes == null || method.Parameters[0].Attributes.Count == 0)) method.Parameters[0].Attributes = this.ExtractAttributes(method.Attributes, AttributeTargets.Parameter); else if (method.Parameters.Count == 2 && (method.Parameters[1].Attributes == null || method.Parameters[1].Attributes.Count == 0)) method.Parameters[1].Attributes = this.ExtractAttributes(method.Attributes, AttributeTargets.Parameter); } } this.currentMethod = savedMethod; this.currentThisParameter = savedThisParameter; this.currentReturnLocal = savedReturnLocal; this.currentReturnLabel = savedReturnLabel; this.currentClosureLocal = savedClosureLocal; this.currentContractPrelude = savedContractPrelude; this.currentContractExceptionalTerminationChecks = savedContractExceptionalTerminationChecks; this.currentExceptionalTerminationException = savedcurrentExceptionalTerminationException; this.currentContractNormalTerminationCheck = savedContractNormalTerminationCheck; return method; }
/// <summary> /// Creates a block containing the given tryBlock and catchBlocks and /// returns it. The method is modified by having new ExceptionHandlers /// added to it which points to the right places in the blocks. /// The type of exception caught by each catch block should be the type /// of the corresponding local l. /// </summary> /// <param name="m">The method in which the try-catch block will be /// inserted into.</param> /// <param name="tryBody">A block of statements that will be the body /// of the try-catch statement.</param> /// <param name="catchBodies">A sequence of blocks; each one contains the /// statements that will be the body of a catch clause on the try-catch statement. /// </param> /// <param name="l">The local into which the exception will be /// assigned. Presumably, the body of the catch clause does something /// with this local.</param> /// <returns>A single block which must be inserted into m by the client. /// </returns> internal static Block CreateTryCatchBlock(Method m, Block tryBody, Block catchBody, Local l) { BlockList bs = new BlockList(1); bs.Add(catchBody); LocalList ls = new LocalList(1); ls.Add(l); return CreateTryCatchBlock(m, tryBody, bs, ls); }
internal static Block CreateTryCatchBlock(Method m, Block tryBody, BlockList catchBodies, LocalList ls) { // The tryCatch holds the try block, the catch blocks, and an empty block that is the // target of an unconditional branch for normal execution to go from the try block // around the catch blocks. if (m.ExceptionHandlers == null) m.ExceptionHandlers = new ExceptionHandlerList(); Block tryCatch = new Block(new StatementList()); Block tryBlock = new Block(new StatementList()); Block afterCatches = new Block(new StatementList(new Statement(NodeType.Nop))); tryBlock.Statements.Add(tryBody); tryBlock.Statements.Add(new Branch(null,afterCatches,false,true,true)); // the EH needs to have a pointer to this block so the writer can // calculate the length of the try block. So it should be the *last* // thing in the try body. Block blockAfterTryBody = new Block(null); tryBlock.Statements.Add(blockAfterTryBody); tryCatch.Statements.Add(tryBlock); for (int i = 0, n = catchBodies.Count; i < n; i++) { // The catchBlock contains the assignment to the local, the catchBody, and then // an empty block that is used in the EH. Block catchBlock = new Block(new StatementList()); Local l = ls[i]; Block catchBody = catchBodies[i]; catchBlock.Statements.Add(new AssignmentStatement(l,new Expression(NodeType.Pop))); catchBlock.Statements.Add(catchBody); // The last thing in each catch block is an empty block that is the target of // BlockAfterHandlerEnd in each exception handler. // It is used in the writer to determine the length of each catch block // so it should be the last thing added to each catch block. Block blockAfterHandlerEnd = new Block(new StatementList()); catchBlock.Statements.Add(blockAfterHandlerEnd); tryCatch.Statements.Add(catchBlock); // add information to the ExceptionHandlers of this method ExceptionHandler exHandler = new ExceptionHandler(); exHandler.TryStartBlock = tryBody; exHandler.BlockAfterTryEnd = blockAfterTryBody; exHandler.HandlerStartBlock = catchBlock; exHandler.BlockAfterHandlerEnd = blockAfterHandlerEnd; exHandler.FilterType = l.Type; exHandler.HandlerType = NodeType.Catch; m.ExceptionHandlers.Add(exHandler); } tryCatch.Statements.Add(afterCatches); return tryCatch; }
public void ClearBody() { lock(Module.GlobalLock) { this.Body = null; this.Instructions = null; this.LocalList = null; } }
private static int FindIndexOfFirstUniqueSuggestion( [NotNull] IList<string> suggestions, ref LocalList<IList<string>> previousSuggestions) { for (int index = 0; index < suggestions.Count; index++) { string currentSuggestion = suggestions[index]; bool isUnique = !previousSuggestions.Any(previous => previous[0] == currentSuggestion); if (isUnique) return index; } return -1; }
private static void CollectUsageRanges([NotNull] IDeclaredElement declaredElement, [NotNull] ITreeNode scope, ref LocalList<DocumentRange> ranges) { foreach (var referenceExpression in scope.Descendants<IReferenceExpression>()) { var currentElement = referenceExpression.Reference.Resolve().DeclaredElement; if (currentElement == null) continue; if (currentElement.Equals(declaredElement)) { var range = referenceExpression.GetDocumentRange(); ranges.Add(range); } } }
/// <summary> /// Default constructor /// </summary> public CilBody() { this.initLocals = true; this.instructions = ThreadSafeListCreator.Create<Instruction>(); this.exceptionHandlers = ThreadSafeListCreator.Create<ExceptionHandler>(); this.localList = new LocalList(); }
/// <summary> /// Constructor /// </summary> /// <param name="initLocals">Init locals flag</param> /// <param name="instructions">All instructions. This instance will own the list.</param> /// <param name="exceptionHandlers">All exception handlers. This instance will own the list.</param> /// <param name="locals">All locals. This instance will own the locals in the list.</param> public CilBody(bool initLocals, IList<Instruction> instructions, IList<ExceptionHandler> exceptionHandlers, IList<Local> locals) { this.initLocals = initLocals; this.instructions = ThreadSafeListCreator.MakeThreadSafe(instructions); this.exceptionHandlers = ThreadSafeListCreator.MakeThreadSafe(exceptionHandlers); this.localList = new LocalList(locals); }
/// <summary> /// Constructor /// </summary> /// <param name="initLocals">Init locals flag</param> /// <param name="instructions">All instructions. This instance will own the list.</param> /// <param name="exceptionHandlers">All exception handlers. This instance will own the list.</param> /// <param name="locals">All locals. This instance will own the locals in the list.</param> public CilBody(bool initLocals, IList<Instruction> instructions, IList<ExceptionHandler> exceptionHandlers, IList<Local> locals) { this.initLocals = initLocals; this.instructions = instructions; this.exceptionHandlers = exceptionHandlers; this.localList = new LocalList(locals); }
private static void MakeFirstSuggestionUniqueWithNumericSuffix( [NotNull] IList<string> suggestions, ref LocalList<IList<string>> previousSuggestions) { string originalSuggestion = suggestions[0]; for (int counter = 1;; counter++) { string suggestion = originalSuggestion + counter.ToString(); bool isUnique = !previousSuggestions.Any(previous => previous[0] == suggestion); if (isUnique) { suggestions[0] = suggestion; return; } } }
private static IEnumerable<ExceptionContent> GetExceptions([NotNull] IDeclaredElement element, [NotNull] PsiLanguageType languageType, [NotNull] IPsiModule psiModule, [NotNull] IModuleReferenceResolveContext resolveContext) { XmlNode xmlDoc = element.GetXMLDoc(true); if (xmlDoc == null) return EmptyList<ExceptionContent>.InstanceList; XmlNodeList exceptionNodes = xmlDoc.SelectNodes("exception"); if (exceptionNodes == null || exceptionNodes.Count == 0) return EmptyList<ExceptionContent>.InstanceList; var exceptions = new LocalList<ExceptionContent>(); foreach (XmlNode exceptionNode in exceptionNodes) { ExceptionContent exceptionContent = TryExtractException(exceptionNode as XmlElement, languageType, psiModule, resolveContext); if (exceptionContent != null) exceptions.Add(exceptionContent); } return exceptions.ResultingList(); }
public virtual void Execute([NotNull] Lifetime lifetime, [NotNull] ITextControl textControl, [NotNull] IList<PrefixExpressionContext> expressions, [NotNull] string postfixText, [NotNull] string chooserTitle, [NotNull] Action<int> continuation) { #pragma warning disable 618 if (Shell.Instance.IsTestShell) #pragma warning restore 618 { continuation(0); return; } var popupMenu = myPopupMenus.CreateWithLifetime(lifetime); popupMenu.Caption.Value = WindowlessControl.Create(chooserTitle); popupMenu.PopupWindowContext = new TextControlPopupWindowContext( lifetime, textControl, myShellLocks, myActionManager); // advise selected element to highlight expression popupMenu.SelectedItemKey.Change.Advise(lifetime, args => { if (!args.HasNew) return; var menuItem = args.New as SimpleMenuItem; if (menuItem == null) return; var range = menuItem.Tag as TextRange?; if (range != null) { UpdateHighlighting(textControl, range.Value); } }); // build menu items from expressions var items = new LocalList<SimpleMenuItem>(expressions.Count); var index = 0; foreach (var expressionContext in expressions) { TextRange range; var expressionText = PresentExpression(expressionContext, postfixText, out range); var itemIndex = index++; // ReSharper disable once UseObjectOrCollectionInitializer var menuItem = new SimpleMenuItem( expressionText, BulbThemedIcons.YellowBulb.Id, () => continuation(itemIndex)); menuItem.Tag = range; items.Add(menuItem); } popupMenu.SetItems(items.ToArray()); var definition = Lifetimes.Define(lifetime); // handle menu close definition.Lifetime.AddAction(() => { UpdateHighlighting(textControl, TextRange.InvalidRange); }); popupMenu.Show(JetPopupMenu.ShowWhen.AutoExecuteIfSingleItem, definition); }
private void ProcessMethod(StatementList setupInteropStatements, Set<DelegateNode> accumDelegateTypes, Method method) { try { if (env.InteropManager.IsImported(null, method)) { AddDelegateTypes(accumDelegateTypes, method); // If constructor: // C(A1 a1, A2 a2) // emit: // var ci = typeof(<this type>).GetConstructor(new Type[] { typeof(A1), typeof(A2) }); // var ctxt = (JSContext)InteropContextManager.CurrentRuntime.CallImportedMethod( // ci, // <import script>, // new object[] { this, a1, a2 }); // C(ctxt, a1, a2) or C(ctxt); // InteropContextManager.CurrentRuntime.CompleteConstruction(ci, this, ctxt); // // If static method: // R C::M(A1 a1, A2 a2) // emit: // return (R)InteropContextManager.CurrentRuntime.CallImportedMethod( // typeof(<this type>).GetMethod("M", new Type[] { typeof(A1), typeof(A2) }), // <import script>, // new object[] { a1, a2 }); // // If instance method: // R C::M(A1 a1, A2 a2) // emit: // return (R)InteropContextManager.GetRuntimeForObject(this).CallImportedMethod( // typeof(<this type>).GetMethod("M", new Type[] { typeof(A1), typeof(A2) }), // <import script>, // new object[] { this, a1, a2 }); var thisExpr = new ThisBinding(ThisExpression(method.DeclaringType), method.SourceContext); var argExprs = new ExpressionList(); if (!method.IsStatic && !(method is InstanceInitializer)) argExprs.Add(thisExpr); foreach (var p in method.Parameters) argExprs.Add (BoxExpression(new ParameterBinding(p, method.SourceContext), env.ObjectType)); var argArray = ArrayExpression(argExprs, env.ObjectType); // Imports are special in a few ways: // - The runtime will never attempt to Invoke the method base. All it needs are the // argument types, static/instance distiction, and method/constructor distinction. // - The call to Runtime::CallImportedMethod will be within the method body // itself. If the method is polymorphic, and/or within a higher-kinded type, then // typeof(<argument type>) will yield the correct runtime type for the argument, taking // account of all type instantiation. We don't need to know the type arguments themselves. // - Private methods may be imported, however Silverlight doesn't provide reflection for // private methods. // For these reasons we build our own simple-minded method base literal to support the // CallImportedMethod call. var methodBaseExpr = SimpleMethodBaseExpression(method); var runtimeExpr = default(Expression); if (method.IsStatic || method is InstanceInitializer) runtimeExpr = new MethodCall (new MemberBinding(null, env.InteropContextManager_GetCurrentRuntimeMethod), new ExpressionList(0)); else runtimeExpr = new MethodCall (new MemberBinding(null, env.InteropContextManager_GetRuntimeForObjectMethod), new ExpressionList(thisExpr)); var si = env.InteropManager.ImportInfo(null, env.GenSym, new JST.Identifier(env.Root), method); var scriptString = si.Script.ToString(false); env.Log(new InteropInfoMessage(RewriterMsgContext.Method(method), "Imported as: " + scriptString)); var scriptExpr = new Literal(scriptString, env.StringType); var statements = method.Body.Statements; var ctor = method as InstanceInitializer; if (ctor != null) { var locals = ctor.LocalList; if (locals == null) { locals = new LocalList(2); ctor.LocalList = locals; } var constructorInfoLocal = new Local(Identifier.For("ci"), env.SimpleMethodBaseType); locals.Add(constructorInfoLocal); var contextLocal = new Local(Identifier.For("ctxt"), env.JSContextType); locals.Add(contextLocal); statements.Add (new AssignmentStatement (new LocalBinding(constructorInfoLocal, ctor.SourceContext), methodBaseExpr)); statements.Add (new AssignmentStatement (new LocalBinding(contextLocal, ctor.SourceContext), CastExpression (new MethodCall (new MemberBinding (runtimeExpr, env.Runtime_CallImportedMethodMethod), new ExpressionList (new LocalBinding(constructorInfoLocal, ctor.SourceContext), scriptExpr, argArray)), env.JSContextType))); var importingCtor = BestImportingConstructor(ctor); var args = new ExpressionList(importingCtor.Parameters.Count); args.Add(new LocalBinding(contextLocal, ctor.SourceContext)); if (importingCtor.Parameters.Count > 1) { for (var i = 0; i < ctor.Parameters.Count; i++) args.Add(new ParameterBinding(ctor.Parameters[i], ctor.SourceContext)); } statements.Add (new ExpressionStatement (new MethodCall(new MemberBinding(thisExpr, importingCtor), args))); statements.Add (new ExpressionStatement (new MethodCall (new MemberBinding(runtimeExpr, env.Runtime_CompleteConstructionMethod), new ExpressionList (new LocalBinding(constructorInfoLocal, ctor.SourceContext), thisExpr, new LocalBinding(contextLocal, ctor.SourceContext))))); statements.Add(new Return()); } else if (method.ReturnType == env.VoidType) { statements.Add (new ExpressionStatement (new MethodCall (new MemberBinding(runtimeExpr, env.Runtime_CallImportedMethodMethod), new ExpressionList(methodBaseExpr, scriptExpr, argArray)))); statements.Add(new ExpressionStatement(new UnaryExpression(null, NodeType.Pop))); statements.Add(new Return()); } else { statements.Add (new Return (CastExpression (new MethodCall (new MemberBinding (runtimeExpr, env.Runtime_CallImportedMethodMethod), new ExpressionList(methodBaseExpr, scriptExpr, argArray)), method.ReturnType))); } TagAsInteropGenerated(method); } if (env.InteropManager.IsExported(null, method)) { AddDelegateTypes(accumDelegateTypes, method); // For each exported method, append to <Module>::SetupInterop() // InteropContextManager.Database.RegisterExport(<method base of M>, <bind to instance>, <cature this>, <export script>); // Exports are special in a few ways: // - Polymorphic methods cannot be exported, so we never need to deal with them. // - The call to Runtime::RegisterExportMethod is outside of the method itself. For instance // methods, the declaring type may be higher-kinded, in which case we must recover the // type arguments from the type of the instance at runtime. Thus at compile-time we // must describe the method in it's higher-kinded declaring type. // - The runtime needs to be able to Invoke the method base. // Thus we are forced to use true MethodBase, MethodInfo and ConstructorInfo, and work-around // limitations of reflection. var si = env.InteropManager.ExportInfo(null, env.GenSym, new JST.Identifier(env.Root), method); var scriptString = si.Script.ToString(false); env.Log(new InteropInfoMessage(RewriterMsgContext.Method(method), "Exported as: " + scriptString)); setupInteropStatements.Add (new ExpressionStatement (new MethodCall (new MemberBinding (DatabaseExpression(), env.InteropDatabase_RegisterExportMethod), new ExpressionList (MethodBaseExpression(method), new Literal(si.BindToInstance, env.BooleanType), new Literal(scriptString, env.StringType))))); } } catch (DefinitionException) { env.Log(new InvalidInteropMessage(RewriterMsgContext.Method(method), "Method contains interop specification errors")); } }
/// <summary> /// Default constructor /// </summary> public CilBody() { this.initLocals = true; this.instructions = new List<Instruction>(); this.exceptionHandlers = new List<ExceptionHandler>(); this.localList = new LocalList(); }