content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; using UnityEngine.UI; using UnityEngine.Analytics; public class GameMaster : MonoBehaviour { public GameObject restartPanel; public Text score; public float timer; private float oldTimer; bool isRunning = true; bool isOver = false; public string nextLevel; public void Start() { oldTimer = timer; Analytics.CustomEvent("StartLevel", new Dictionary<string, object>{ {"levelNumber", SceneManager.GetActiveScene()} }); } public void Update() { if(!isOver) { if(timer < 0) { isRunning = false; } if(isRunning) { timer -= Time.deltaTime; score.text = "Tempo: " + Math.Round(timer, 2); } else { SceneManager.LoadScene(nextLevel); } } } public void GameOver() { Analytics.CustomEvent("gameOver", new Dictionary<string, object>{ { "tempo", timer }, { "level", SceneManager.GetActiveScene()} }); isOver = true; Delay(); } public void Delay() { restartPanel.SetActive(true); } public void Restart() { SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex); } public void GoToMainMenu() { SceneManager.LoadScene("MainMenu"); } }
23.235294
75
0.549367
[ "MIT" ]
thiagos98/Drag-Zombies
Assets/Scripts/GameMaster.cs
1,582
C#
namespace LigerShark.Templates.Extensions { using System; using System.IO; using System.Net.Http; using System.Threading.Tasks; public static class HttpContentExtensions { public static async Task ReadAsFileAsync(this HttpContent content, string filename, bool overwrite) { string pathname = Path.GetFullPath(filename); if (!overwrite && File.Exists(filename)) { throw new InvalidOperationException(string.Format("File {0} already exists.", pathname)); } using (var fileStream = new FileStream(pathname, FileMode.Create, FileAccess.Write, FileShare.None)) { await content.CopyToAsync(fileStream); fileStream.Close(); } } } }
36.952381
114
0.636598
[ "Apache-2.0" ]
AesisGit/side-waffle
LigerShark.Templates/Extensions/HttpContentExtensions.cs
778
C#
namespace Shared.Domains.Enumerations { public enum QueryType { Equal, LessThan, GreaterThan, LessThanOrEqual, GreaterThanOrEqual } }
17.181818
37
0.582011
[ "MIT" ]
RomeshAbeyawardena/Shared
Shared.Domains/Enumerations/QueryType.cs
189
C#
using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Threading.Tasks; using Iris.DataLayer; using Iris.DomainClasses; using Iris.ServiceLayer.Contracts; using Microsoft.AspNet.Identity; namespace Iris.ServiceLayer { public class ApplicationRoleManager : RoleManager<CustomRole, int>, IApplicationRoleManager { #region Fields private readonly IUnitOfWork _uow; private readonly IRoleStore<CustomRole, int> _roleStore; private readonly IDbSet<ApplicationUser> _users; #endregion #region Constractors public ApplicationRoleManager(IUnitOfWork uow, IRoleStore<CustomRole, int> roleStore) : base(roleStore) { _uow = uow; _roleStore = roleStore; _users = _uow.Set<ApplicationUser>(); } #endregion #region FindRoleByName public CustomRole FindRoleByName(string roleName) { return this.FindByName(roleName); // RoleManagerExtensions } #endregion #region CreateRole public IdentityResult CreateRole(CustomRole role) { return this.Create(role); // RoleManagerExtensions } #endregion #region GetCustomUsersInRole public IList<CustomUserRole> GetCustomUsersInRole(string roleName) { return this.Roles.Where(role => role.Name == roleName) .SelectMany(role => role.Users) .ToList(); // = this.FindByName(roleName).Users } #endregion #region GetApplicationUsersInRole public IList<ApplicationUser> GetApplicationUsersInRole(string roleName) { var roleUserIdsQuery = from role in this.Roles where role.Name == roleName from user in role.Users select user.UserId; return _users.Where(applicationUser => roleUserIdsQuery.Contains(applicationUser.Id)) .ToList(); } #endregion #region FindUserRoles public IList<CustomRole> FindUserRoles(int userId) { var userRolesQuery = from role in this.Roles from user in role.Users where user.UserId == userId select role; return userRolesQuery.OrderBy(x => x.Name).ToList(); } #endregion #region GetRolesForUser public string[] GetRolesForUser(int userId) { var roles = FindUserRoles(userId); if (roles == null || !roles.Any()) { return new string[] { }; } return roles.Select(x => x.Name).ToArray(); } #endregion #region IsUserInRole public bool IsUserInRole(int userId, string roleName) { var userRolesQuery = from role in this.Roles where role.Name == roleName from user in role.Users where user.UserId == userId select role; var userRole = userRolesQuery.FirstOrDefault(); return userRole != null; } #endregion #region GetAllCustomRolesAsync public Task<List<CustomRole>> GetAllCustomRolesAsync() { return this.Roles.ToListAsync(); } #endregion } }
32.045045
97
0.562272
[ "MIT" ]
AmirChabok/IrisStore
Iris.ServiceLayer/ApplicationRoleManager.cs
3,559
C#
using GeneXus.Utils; using System; using System.Collections.Generic; using System.Drawing; namespace GeneXus.WebControls { public class WebControl { public string ID { get; internal set; } public Color ForeColor { get; internal set; } public Color BackColor { get; internal set; } public Unit BorderWidth { get; internal set; } public Unit Width { get; internal set; } public Unit Height { get; internal set; } public FontInfo Font { get; internal set; } public bool Enabled { get; internal set; } public bool Visible { get; internal set; } public string ToolTip { get; internal set; } public string CssClass { get; internal set; } public Dictionary<string, string> Attributes { get; internal set; } public void RenderControl(HtmlTextWriter controlOutputWriter) { } public string Text { get; internal set; } public Dictionary<string,string> Style { get; set; } } public class TextBox : WebControl { public int MaxLength { get; internal set; } public int Columns { get; internal set; } public object TextMode { get; internal set; } public int Rows { get; internal set; } } public enum TextBoxMode { // // Summary: // Represents single-line entry mode. SingleLine = 0, // // Summary: // Represents multiline entry mode. MultiLine = 1, // // Summary: // Represents password entry mode. Password = 2, // // Summary: // Represents color entry mode. Color = 3, // // Summary: // Represents date entry mode. Date = 4, // // Summary: // Represents date-time entry mode. DateTime = 5, // // Summary: // Represents local date-time entry mode. DateTimeLocal = 6, // // Summary: // Represents email address entry mode. Email = 7, // // Summary: // Represents month entry mode. Month = 8, // // Summary: // Represents number entry mode. Number = 9, // // Summary: // Represents numeric range entry mode. Range = 10, // // Summary: // Represents search string entry mode. Search = 11, // // Summary: // Represents phone number entry mode. Phone = 12, // // Summary: // Represents time entry mode. Time = 13, // // Summary: // Represents URL entry mode. Url = 14, // // Summary: // Represents week entry mode. Week = 15 } public class HyperLink : WebControl { public string NavigateUrl { get; internal set; } public string Target { get; internal set; } } public class LiteralControl { public string ID { get; internal set; } public string Text { get; internal set; } public bool Visible { get; internal set; } internal void RenderControl(HtmlTextWriter controlOutputWriter) { throw new NotImplementedException(); } } }
23.5
69
0.64515
[ "Apache-2.0" ]
genexuslabs/DotNetClasses
dotnet/src/dotnetcore/GxClasses.Web/View/WebControl.cs
2,773
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Shared.Utilities { /// <summary> /// Helper class to analyze the semantic effects of a speculated syntax node replacement on the parenting nodes. /// Given an expression node from a syntax tree and a new expression from a different syntax tree, /// it replaces the expression with the new expression to create a speculated syntax tree. /// It uses the original tree's semantic model to create a speculative semantic model and verifies that /// the syntax replacement doesn't break the semantics of any parenting nodes of the original expression. /// </summary> internal abstract class AbstractSpeculationAnalyzer< TExpressionSyntax, TTypeSyntax, TAttributeSyntax, TArgumentSyntax, TForEachStatementSyntax, TThrowStatementSyntax, TConversion> where TExpressionSyntax : SyntaxNode where TTypeSyntax : TExpressionSyntax where TAttributeSyntax : SyntaxNode where TArgumentSyntax : SyntaxNode where TForEachStatementSyntax : SyntaxNode where TThrowStatementSyntax : SyntaxNode where TConversion : struct { private readonly TExpressionSyntax _expression; private readonly TExpressionSyntax _newExpressionForReplace; private readonly SemanticModel _semanticModel; private readonly CancellationToken _cancellationToken; private readonly bool _skipVerificationForReplacedNode; private readonly bool _failOnOverloadResolutionFailuresInOriginalCode; private readonly bool _isNewSemanticModelSpeculativeModel; private SyntaxNode? _lazySemanticRootOfOriginalExpression; private TExpressionSyntax? _lazyReplacedExpression; private SyntaxNode? _lazySemanticRootOfReplacedExpression; private SemanticModel? _lazySpeculativeSemanticModel; /// <summary> /// Creates a semantic analyzer for speculative syntax replacement. /// </summary> /// <param name="expression">Original expression to be replaced.</param> /// <param name="newExpression">New expression to replace the original expression.</param> /// <param name="semanticModel">Semantic model of <paramref name="expression"/> node's syntax tree.</param> /// <param name="cancellationToken">Cancellation token.</param> /// <param name="skipVerificationForReplacedNode"> /// True if semantic analysis should be skipped for the replaced node and performed starting from parent of the original and replaced nodes. /// This could be the case when custom verifications are required to be done by the caller or /// semantics of the replaced expression are different from the original expression. /// </param> /// <param name="failOnOverloadResolutionFailuresInOriginalCode"> /// True if semantic analysis should fail when any of the invocation expression ancestors of <paramref name="expression"/> in original code has overload resolution failures. /// </param> public AbstractSpeculationAnalyzer( TExpressionSyntax expression, TExpressionSyntax newExpression, SemanticModel semanticModel, CancellationToken cancellationToken, bool skipVerificationForReplacedNode = false, bool failOnOverloadResolutionFailuresInOriginalCode = false) { _expression = expression; _newExpressionForReplace = newExpression; _semanticModel = semanticModel; _cancellationToken = cancellationToken; _skipVerificationForReplacedNode = skipVerificationForReplacedNode; _failOnOverloadResolutionFailuresInOriginalCode = failOnOverloadResolutionFailuresInOriginalCode; _isNewSemanticModelSpeculativeModel = true; _lazyReplacedExpression = null; _lazySemanticRootOfOriginalExpression = null; _lazySemanticRootOfReplacedExpression = null; _lazySpeculativeSemanticModel = null; } /// <summary> /// Original expression to be replaced. /// </summary> public TExpressionSyntax OriginalExpression => _expression; /// <summary> /// First ancestor of <see cref="OriginalExpression"/> which is either a statement, attribute, constructor initializer, /// field initializer, default parameter initializer or type syntax node. /// It serves as the root node for all semantic analysis for this syntax replacement. /// </summary> public SyntaxNode SemanticRootOfOriginalExpression { get { if (_lazySemanticRootOfOriginalExpression == null) { _lazySemanticRootOfOriginalExpression = GetSemanticRootForSpeculation(this.OriginalExpression); RoslynDebug.AssertNotNull(_lazySemanticRootOfOriginalExpression); } return _lazySemanticRootOfOriginalExpression; } } /// <summary> /// Semantic model for the syntax tree corresponding to <see cref="OriginalExpression"/> /// </summary> public SemanticModel OriginalSemanticModel => _semanticModel; /// <summary> /// Node which replaces the <see cref="OriginalExpression"/>. /// Note that this node is a cloned version of <see cref="_newExpressionForReplace"/> node, which has been re-parented /// under the node to be speculated, i.e. <see cref="SemanticRootOfReplacedExpression"/>. /// </summary> public TExpressionSyntax ReplacedExpression { get { EnsureReplacedExpressionAndSemanticRoot(); return _lazyReplacedExpression; } } /// <summary> /// Node created by replacing <see cref="OriginalExpression"/> under <see cref="SemanticRootOfOriginalExpression"/> node. /// This node is used as the argument to the GetSpeculativeSemanticModel API and serves as the root node for all /// semantic analysis of the speculated tree. /// </summary> public SyntaxNode SemanticRootOfReplacedExpression { get { EnsureReplacedExpressionAndSemanticRoot(); return _lazySemanticRootOfReplacedExpression; } } /// <summary> /// Speculative semantic model used for analyzing the semantics of the new tree. /// </summary> public SemanticModel SpeculativeSemanticModel { get { EnsureSpeculativeSemanticModel(); return _lazySpeculativeSemanticModel; } } public CancellationToken CancellationToken => _cancellationToken; protected abstract SyntaxNode GetSemanticRootForSpeculation(TExpressionSyntax expression); protected virtual SyntaxNode GetSemanticRootOfReplacedExpression(SyntaxNode semanticRootOfOriginalExpression, TExpressionSyntax annotatedReplacedExpression) => semanticRootOfOriginalExpression.ReplaceNode(this.OriginalExpression, annotatedReplacedExpression); [MemberNotNull(nameof(_lazySemanticRootOfReplacedExpression), nameof(_lazyReplacedExpression))] private void EnsureReplacedExpressionAndSemanticRoot() { if (_lazySemanticRootOfReplacedExpression == null) { // Because the new expression will change identity once we replace the old // expression in its parent, we annotate it here to allow us to get back to // it after replace. var annotation = new SyntaxAnnotation(); var annotatedExpression = _newExpressionForReplace.WithAdditionalAnnotations(annotation); _lazySemanticRootOfReplacedExpression = GetSemanticRootOfReplacedExpression(this.SemanticRootOfOriginalExpression, annotatedExpression); _lazyReplacedExpression = (TExpressionSyntax)_lazySemanticRootOfReplacedExpression.GetAnnotatedNodesAndTokens(annotation).Single().AsNode()!; } else { RoslynDebug.AssertNotNull(_lazyReplacedExpression); } } [Conditional("DEBUG")] protected abstract void ValidateSpeculativeSemanticModel(SemanticModel speculativeSemanticModel, SyntaxNode nodeToSpeculate); [MemberNotNull(nameof(_lazySpeculativeSemanticModel))] private void EnsureSpeculativeSemanticModel() { if (_lazySpeculativeSemanticModel == null) { var nodeToSpeculate = this.SemanticRootOfReplacedExpression; _lazySpeculativeSemanticModel = CreateSpeculativeSemanticModel(this.SemanticRootOfOriginalExpression, nodeToSpeculate, _semanticModel); ValidateSpeculativeSemanticModel(_lazySpeculativeSemanticModel, nodeToSpeculate); } } protected abstract SemanticModel CreateSpeculativeSemanticModel(SyntaxNode originalNode, SyntaxNode nodeToSpeculate, SemanticModel semanticModel); #region Semantic comparison helpers protected virtual bool ReplacementIntroducesErrorType(TExpressionSyntax originalExpression, TExpressionSyntax newExpression) { RoslynDebug.AssertNotNull(originalExpression); Debug.Assert(this.SemanticRootOfOriginalExpression.DescendantNodesAndSelf().Contains(originalExpression)); RoslynDebug.AssertNotNull(newExpression); Debug.Assert(this.SemanticRootOfReplacedExpression.DescendantNodesAndSelf().Contains(newExpression)); var originalTypeInfo = this.OriginalSemanticModel.GetTypeInfo(originalExpression); var newTypeInfo = this.SpeculativeSemanticModel.GetTypeInfo(newExpression); if (originalTypeInfo.Type == null) { return false; } return newTypeInfo.Type == null || (newTypeInfo.Type.IsErrorType() && !originalTypeInfo.Type.IsErrorType()); } protected bool TypesAreCompatible(TExpressionSyntax originalExpression, TExpressionSyntax newExpression) { RoslynDebug.AssertNotNull(originalExpression); Debug.Assert(this.SemanticRootOfOriginalExpression.DescendantNodesAndSelf().Contains(originalExpression)); RoslynDebug.AssertNotNull(newExpression); Debug.Assert(this.SemanticRootOfReplacedExpression.DescendantNodesAndSelf().Contains(newExpression)); var originalTypeInfo = this.OriginalSemanticModel.GetTypeInfo(originalExpression); var newTypeInfo = this.SpeculativeSemanticModel.GetTypeInfo(newExpression); return SymbolsAreCompatible(originalTypeInfo.Type, newTypeInfo.Type); } protected bool ConvertedTypesAreCompatible(TExpressionSyntax originalExpression, TExpressionSyntax newExpression) { RoslynDebug.AssertNotNull(originalExpression); Debug.Assert(this.SemanticRootOfOriginalExpression.DescendantNodesAndSelf().Contains(originalExpression)); RoslynDebug.AssertNotNull(newExpression); Debug.Assert(this.SemanticRootOfReplacedExpression.DescendantNodesAndSelf().Contains(newExpression)); var originalTypeInfo = this.OriginalSemanticModel.GetTypeInfo(originalExpression); var newTypeInfo = this.SpeculativeSemanticModel.GetTypeInfo(newExpression); return SymbolsAreCompatible(originalTypeInfo.ConvertedType, newTypeInfo.ConvertedType); } protected bool ImplicitConversionsAreCompatible(TExpressionSyntax originalExpression, TExpressionSyntax newExpression) { RoslynDebug.AssertNotNull(originalExpression); Debug.Assert(this.SemanticRootOfOriginalExpression.DescendantNodesAndSelf().Contains(originalExpression)); RoslynDebug.AssertNotNull(newExpression); Debug.Assert(this.SemanticRootOfReplacedExpression.DescendantNodesAndSelf().Contains(newExpression)); return ConversionsAreCompatible(this.OriginalSemanticModel, originalExpression, this.SpeculativeSemanticModel, newExpression); } private bool ImplicitConversionsAreCompatible(TExpressionSyntax originalExpression, ITypeSymbol originalTargetType, TExpressionSyntax newExpression, ITypeSymbol newTargetType) { RoslynDebug.AssertNotNull(originalExpression); Debug.Assert(this.SemanticRootOfOriginalExpression.DescendantNodesAndSelf().Contains(originalExpression)); RoslynDebug.AssertNotNull(newExpression); Debug.Assert(this.SemanticRootOfReplacedExpression.DescendantNodesAndSelf().Contains(newExpression)); RoslynDebug.AssertNotNull(originalTargetType); RoslynDebug.AssertNotNull(newTargetType); return ConversionsAreCompatible(originalExpression, originalTargetType, newExpression, newTargetType); } protected abstract bool ConversionsAreCompatible(SemanticModel model1, TExpressionSyntax expression1, SemanticModel model2, TExpressionSyntax expression2); protected abstract bool ConversionsAreCompatible(TExpressionSyntax originalExpression, ITypeSymbol originalTargetType, TExpressionSyntax newExpression, ITypeSymbol newTargetType); protected bool SymbolsAreCompatible(SyntaxNode originalNode, SyntaxNode newNode, bool requireNonNullSymbols = false) { RoslynDebug.AssertNotNull(originalNode); Debug.Assert(this.SemanticRootOfOriginalExpression.DescendantNodesAndSelf().Contains(originalNode)); RoslynDebug.AssertNotNull(newNode); Debug.Assert(this.SemanticRootOfReplacedExpression.DescendantNodesAndSelf().Contains(newNode)); var originalSymbolInfo = this.OriginalSemanticModel.GetSymbolInfo(originalNode); var newSymbolInfo = this.SpeculativeSemanticModel.GetSymbolInfo(newNode); return SymbolInfosAreCompatible(originalSymbolInfo, newSymbolInfo, requireNonNullSymbols); } public static bool SymbolInfosAreCompatible(SymbolInfo originalSymbolInfo, SymbolInfo newSymbolInfo, bool performEquivalenceCheck, bool requireNonNullSymbols = false) { return originalSymbolInfo.CandidateReason == newSymbolInfo.CandidateReason && SymbolsAreCompatibleCore(originalSymbolInfo.Symbol, newSymbolInfo.Symbol, performEquivalenceCheck, requireNonNullSymbols); } protected bool SymbolInfosAreCompatible(SymbolInfo originalSymbolInfo, SymbolInfo newSymbolInfo, bool requireNonNullSymbols = false) => SymbolInfosAreCompatible(originalSymbolInfo, newSymbolInfo, performEquivalenceCheck: !_isNewSemanticModelSpeculativeModel, requireNonNullSymbols: requireNonNullSymbols); protected bool SymbolsAreCompatible(ISymbol? symbol, ISymbol? newSymbol, bool requireNonNullSymbols = false) => SymbolsAreCompatibleCore(symbol, newSymbol, performEquivalenceCheck: !_isNewSemanticModelSpeculativeModel, requireNonNullSymbols: requireNonNullSymbols); private static bool SymbolsAreCompatibleCore( ISymbol? symbol, ISymbol? newSymbol, bool performEquivalenceCheck, bool requireNonNullSymbols = false) { if (symbol == null && newSymbol == null) { return !requireNonNullSymbols; } if (symbol == null || newSymbol == null) { return false; } if (symbol.IsReducedExtension()) { symbol = ((IMethodSymbol)symbol).GetConstructedReducedFrom()!; } if (newSymbol.IsReducedExtension()) { newSymbol = ((IMethodSymbol)newSymbol).GetConstructedReducedFrom()!; } // TODO: Lambda function comparison performs syntax equality, hence is non-trivial to compare lambda methods across different compilations. // For now, just assume they are equal. if (symbol.IsAnonymousFunction()) { return newSymbol.IsAnonymousFunction(); } if (performEquivalenceCheck) { // We are comparing symbols across two semantic models (where neither is the speculative model of other one). // We will use the SymbolEquivalenceComparer to check if symbols are equivalent. return CompareAcrossSemanticModels(symbol, newSymbol); } if (symbol.Equals(newSymbol, SymbolEqualityComparer.IncludeNullability)) { return true; } if (symbol is IMethodSymbol methodSymbol && newSymbol is IMethodSymbol newMethodSymbol) { // If we have local functions, we can't use normal symbol equality for them (since that checks locations). // Have to defer to SymbolEquivalence instead. if (methodSymbol.MethodKind == MethodKind.LocalFunction && newMethodSymbol.MethodKind == MethodKind.LocalFunction) return CompareAcrossSemanticModels(methodSymbol, newMethodSymbol); // Handle equivalence of special built-in comparison operators between enum types and // it's underlying enum type. if (methodSymbol.TryGetPredefinedComparisonOperator(out var originalOp) && newMethodSymbol.TryGetPredefinedComparisonOperator(out var newOp) && originalOp == newOp) { var type = methodSymbol.ContainingType; var newType = newMethodSymbol.ContainingType; if (type != null && newType != null) { if (EnumTypesAreCompatible(type, newType) || EnumTypesAreCompatible(newType, type)) { return true; } } } } return false; } private static bool CompareAcrossSemanticModels(ISymbol symbol, ISymbol newSymbol) { // SymbolEquivalenceComparer performs Location equality checks for locals, labels, range-variables and local // functions. As we are comparing symbols from different semantic models, locations will differ. Hence // perform minimal checks for these symbol kinds. if (symbol.Kind != newSymbol.Kind) return false; if (symbol is ILocalSymbol localSymbol && newSymbol is ILocalSymbol newLocalSymbol) { return newSymbol.IsImplicitlyDeclared == symbol.IsImplicitlyDeclared && symbol.Name == newSymbol.Name && CompareAcrossSemanticModels(localSymbol.Type, newLocalSymbol.Type); } if (symbol is ILabelSymbol && newSymbol is ILabelSymbol) return symbol.Name == newSymbol.Name; if (symbol is IRangeVariableSymbol && newSymbol is IRangeVariableSymbol) return symbol.Name == newSymbol.Name; if (symbol is IParameterSymbol parameterSymbol && newSymbol is IParameterSymbol newParameterSymbol && parameterSymbol.ContainingSymbol.IsAnonymousOrLocalFunction() && newParameterSymbol.ContainingSymbol.IsAnonymousOrLocalFunction()) { return symbol.Name == newSymbol.Name && parameterSymbol.IsRefOrOut() == newParameterSymbol.IsRefOrOut() && CompareAcrossSemanticModels(parameterSymbol.Type, newParameterSymbol.Type); } if (symbol is IMethodSymbol methodSymbol && newSymbol is IMethodSymbol newMethodSymbol && methodSymbol.IsLocalFunction() && newMethodSymbol.IsLocalFunction()) { return symbol.Name == newSymbol.Name && methodSymbol.Parameters.Length == newMethodSymbol.Parameters.Length && CompareAcrossSemanticModels(methodSymbol.ReturnType, newMethodSymbol.ReturnType) && methodSymbol.Parameters.Zip(newMethodSymbol.Parameters, (p1, p2) => (p1, p2)).All( t => CompareAcrossSemanticModels(t.p1, t.p2)); } return SymbolEquivalenceComparer.Instance.Equals(symbol, newSymbol); } private static bool EnumTypesAreCompatible(INamedTypeSymbol type1, INamedTypeSymbol type2) => type1.IsEnumType() && type1.EnumUnderlyingType?.SpecialType == type2.SpecialType; #endregion /// <summary> /// Determines whether performing the given syntax replacement will change the semantics of any parenting expressions /// by performing a bottom up walk from the <see cref="OriginalExpression"/> up to <see cref="SemanticRootOfOriginalExpression"/> /// in the original tree and simultaneously walking bottom up from <see cref="ReplacedExpression"/> up to <see cref="SemanticRootOfReplacedExpression"/> /// in the speculated syntax tree and performing appropriate semantic comparisons. /// </summary> public bool ReplacementChangesSemantics() { if (this.SemanticRootOfOriginalExpression is TTypeSyntax) { var originalType = (TTypeSyntax)this.OriginalExpression; var newType = (TTypeSyntax)this.ReplacedExpression; return ReplacementBreaksTypeResolution(originalType, newType, useSpeculativeModel: false); } return ReplacementChangesSemantics( currentOriginalNode: this.OriginalExpression, currentReplacedNode: this.ReplacedExpression, originalRoot: this.SemanticRootOfOriginalExpression, skipVerificationForCurrentNode: _skipVerificationForReplacedNode); } protected abstract bool IsParenthesizedExpression([NotNullWhen(true)] SyntaxNode? node); protected bool ReplacementChangesSemantics(SyntaxNode currentOriginalNode, SyntaxNode currentReplacedNode, SyntaxNode originalRoot, bool skipVerificationForCurrentNode) { if (this.SpeculativeSemanticModel == null) { // This is possible for some broken code scenarios with parse errors, bail out gracefully here. return true; } SyntaxNode? previousOriginalNode = null, previousReplacedNode = null; while (true) { if (!skipVerificationForCurrentNode && ReplacementChangesSemanticsForNode( currentOriginalNode, currentReplacedNode, previousOriginalNode, previousReplacedNode)) { return true; } if (currentOriginalNode == originalRoot) { break; } RoslynDebug.AssertNotNull(currentOriginalNode.Parent); RoslynDebug.AssertNotNull(currentReplacedNode.Parent); previousOriginalNode = currentOriginalNode; previousReplacedNode = currentReplacedNode; currentOriginalNode = currentOriginalNode.Parent; currentReplacedNode = currentReplacedNode.Parent; skipVerificationForCurrentNode = skipVerificationForCurrentNode && IsParenthesizedExpression(currentReplacedNode); } return false; } /// <summary> /// Checks whether the semantic symbols for the <see cref="OriginalExpression"/> and <see cref="ReplacedExpression"/> are non-null and compatible. /// </summary> /// <returns></returns> public bool SymbolsForOriginalAndReplacedNodesAreCompatible() { if (this.SpeculativeSemanticModel == null) { // This is possible for some broken code scenarios with parse errors, bail out gracefully here. return false; } return SymbolsAreCompatible(this.OriginalExpression, this.ReplacedExpression, requireNonNullSymbols: true); } protected abstract bool ReplacementChangesSemanticsForNodeLanguageSpecific(SyntaxNode currentOriginalNode, SyntaxNode currentReplacedNode, SyntaxNode? previousOriginalNode, SyntaxNode? previousReplacedNode); private bool ReplacementChangesSemanticsForNode(SyntaxNode currentOriginalNode, SyntaxNode currentReplacedNode, SyntaxNode? previousOriginalNode, SyntaxNode? previousReplacedNode) { Debug.Assert(previousOriginalNode == null || previousOriginalNode.Parent == currentOriginalNode); Debug.Assert(previousReplacedNode == null || previousReplacedNode.Parent == currentReplacedNode); if (ExpressionMightReferenceMember(currentOriginalNode)) { // If replacing the node will result in a change in overload resolution, we won't remove it. var originalExpression = (TExpressionSyntax)currentOriginalNode; var newExpression = (TExpressionSyntax)currentReplacedNode; if (ReplacementBreaksExpression(originalExpression, newExpression)) { return true; } if (ReplacementBreaksSystemObjectMethodResolution(currentOriginalNode, currentReplacedNode, previousOriginalNode, previousReplacedNode)) { return true; } return !ImplicitConversionsAreCompatible(originalExpression, newExpression); } else if (currentOriginalNode is TForEachStatementSyntax originalForEachStatement) { var newForEachStatement = (TForEachStatementSyntax)currentReplacedNode; return ReplacementBreaksForEachStatement(originalForEachStatement, newForEachStatement); } else if (currentOriginalNode is TAttributeSyntax originalAttribute) { var newAttribute = (TAttributeSyntax)currentReplacedNode; return ReplacementBreaksAttribute(originalAttribute, newAttribute); } else if (currentOriginalNode is TThrowStatementSyntax originalThrowStatement) { var newThrowStatement = (TThrowStatementSyntax)currentReplacedNode; return ReplacementBreaksThrowStatement(originalThrowStatement, newThrowStatement); } else if (ReplacementChangesSemanticsForNodeLanguageSpecific(currentOriginalNode, currentReplacedNode, previousOriginalNode, previousReplacedNode)) { return true; } if (currentOriginalNode is TTypeSyntax originalType) { var newType = (TTypeSyntax)currentReplacedNode; return ReplacementBreaksTypeResolution(originalType, newType); } else if (currentOriginalNode is TExpressionSyntax originalExpression) { var newExpression = (TExpressionSyntax)currentReplacedNode; if (!ImplicitConversionsAreCompatible(originalExpression, newExpression) || ReplacementIntroducesErrorType(originalExpression, newExpression)) { return true; } } return false; } /// <summary> /// Determine if removing the cast could cause the semantics of System.Object method call to change. /// E.g. Dim b = CStr(1).GetType() is necessary, but the GetType method symbol info resolves to the same with or without the cast. /// </summary> private bool ReplacementBreaksSystemObjectMethodResolution(SyntaxNode currentOriginalNode, SyntaxNode currentReplacedNode, [NotNullWhen(true)] SyntaxNode? previousOriginalNode, [NotNullWhen(true)] SyntaxNode? previousReplacedNode) { if (previousOriginalNode != null && previousReplacedNode != null) { var originalExpressionSymbol = this.OriginalSemanticModel.GetSymbolInfo(currentOriginalNode).Symbol; var replacedExpressionSymbol = this.SpeculativeSemanticModel.GetSymbolInfo(currentReplacedNode).Symbol; if (IsSymbolSystemObjectInstanceMethod(originalExpressionSymbol) && IsSymbolSystemObjectInstanceMethod(replacedExpressionSymbol)) { var previousOriginalType = this.OriginalSemanticModel.GetTypeInfo(previousOriginalNode).Type; var previousReplacedType = this.SpeculativeSemanticModel.GetTypeInfo(previousReplacedNode).Type; if (previousReplacedType != null && previousOriginalType != null) { return !previousReplacedType.InheritsFromOrEquals(previousOriginalType); } } } return false; } /// <summary> /// Determines if the symbol is a non-overridable, non static method on System.Object (e.g. GetType) /// </summary> private static bool IsSymbolSystemObjectInstanceMethod([NotNullWhen(true)] ISymbol? symbol) { return symbol != null && symbol.IsKind(SymbolKind.Method) && symbol.ContainingType.SpecialType == SpecialType.System_Object && !symbol.IsOverridable() && !symbol.IsStaticType(); } private bool ReplacementBreaksAttribute(TAttributeSyntax attribute, TAttributeSyntax newAttribute) { var attributeSym = this.OriginalSemanticModel.GetSymbolInfo(attribute).Symbol; var newAttributeSym = this.SpeculativeSemanticModel.GetSymbolInfo(newAttribute).Symbol; return !SymbolsAreCompatible(attributeSym, newAttributeSym); } protected abstract TExpressionSyntax GetForEachStatementExpression(TForEachStatementSyntax forEachStatement); protected abstract bool IsForEachTypeInferred(TForEachStatementSyntax forEachStatement, SemanticModel semanticModel); private bool ReplacementBreaksForEachStatement(TForEachStatementSyntax forEachStatement, TForEachStatementSyntax newForEachStatement) { var forEachExpression = GetForEachStatementExpression(forEachStatement); if (forEachExpression.IsMissing || !forEachExpression.Span.Contains(_expression.SpanStart)) { return false; } // inferred variable type compatible if (IsForEachTypeInferred(forEachStatement, _semanticModel)) { var local = (ILocalSymbol)_semanticModel.GetRequiredDeclaredSymbol(forEachStatement, _cancellationToken); var newLocal = (ILocalSymbol)this.SpeculativeSemanticModel.GetRequiredDeclaredSymbol(newForEachStatement, _cancellationToken); if (!SymbolsAreCompatible(local.Type, newLocal.Type)) { return true; } } GetForEachSymbols(this.OriginalSemanticModel, forEachStatement, out var originalGetEnumerator, out var originalElementType); GetForEachSymbols(this.SpeculativeSemanticModel, newForEachStatement, out var newGetEnumerator, out var newElementType); var newForEachExpression = GetForEachStatementExpression(newForEachStatement); if (ReplacementBreaksForEachGetEnumerator(originalGetEnumerator, newGetEnumerator, newForEachExpression) || !ForEachConversionsAreCompatible(this.OriginalSemanticModel, forEachStatement, this.SpeculativeSemanticModel, newForEachStatement) || !SymbolsAreCompatible(originalElementType, newElementType)) { return true; } return false; } protected abstract bool ForEachConversionsAreCompatible(SemanticModel originalModel, TForEachStatementSyntax originalForEach, SemanticModel newModel, TForEachStatementSyntax newForEach); protected abstract void GetForEachSymbols(SemanticModel model, TForEachStatementSyntax forEach, out IMethodSymbol getEnumeratorMethod, out ITypeSymbol elementType); private bool ReplacementBreaksForEachGetEnumerator(IMethodSymbol getEnumerator, IMethodSymbol newGetEnumerator, TExpressionSyntax newForEachStatementExpression) { if (getEnumerator == null && newGetEnumerator == null) { return false; } if (getEnumerator == null || newGetEnumerator == null) { return true; } if (getEnumerator.ToSignatureDisplayString() != newGetEnumerator.ToSignatureDisplayString()) { // Note this is likely an interface member from IEnumerable but the new member may be a // GetEnumerator method on a specific type. if (getEnumerator.IsImplementableMember()) { var expressionType = this.SpeculativeSemanticModel.GetTypeInfo(newForEachStatementExpression, _cancellationToken).ConvertedType; if (expressionType != null) { var implementationMember = expressionType.FindImplementationForInterfaceMember(getEnumerator); if (implementationMember != null) { if (implementationMember.ToSignatureDisplayString() != newGetEnumerator.ToSignatureDisplayString()) { return false; } } } } return true; } return false; } protected abstract TExpressionSyntax GetThrowStatementExpression(TThrowStatementSyntax throwStatement); private bool ReplacementBreaksThrowStatement(TThrowStatementSyntax originalThrowStatement, TThrowStatementSyntax newThrowStatement) { var originalThrowExpression = GetThrowStatementExpression(originalThrowStatement); var originalThrowExpressionType = this.OriginalSemanticModel.GetTypeInfo(originalThrowExpression).Type; var newThrowExpression = GetThrowStatementExpression(newThrowStatement); var newThrowExpressionType = this.SpeculativeSemanticModel.GetTypeInfo(newThrowExpression).Type; // C# language specification requires that type of the expression passed to ThrowStatement is or derives from System.Exception. return originalThrowExpressionType.IsOrDerivesFromExceptionType(this.OriginalSemanticModel.Compilation) != newThrowExpressionType.IsOrDerivesFromExceptionType(this.SpeculativeSemanticModel.Compilation); } protected abstract bool IsInNamespaceOrTypeContext(TExpressionSyntax node); private bool ReplacementBreaksTypeResolution(TTypeSyntax type, TTypeSyntax newType, bool useSpeculativeModel = true) { var symbol = this.OriginalSemanticModel.GetSymbolInfo(type).Symbol; ISymbol? newSymbol; if (useSpeculativeModel) { newSymbol = this.SpeculativeSemanticModel.GetSymbolInfo(newType, _cancellationToken).Symbol; } else { var bindingOption = IsInNamespaceOrTypeContext(type) ? SpeculativeBindingOption.BindAsTypeOrNamespace : SpeculativeBindingOption.BindAsExpression; newSymbol = this.OriginalSemanticModel.GetSpeculativeSymbolInfo(type.SpanStart, newType, bindingOption).Symbol; } return symbol != null && !SymbolsAreCompatible(symbol, newSymbol); } protected abstract bool ExpressionMightReferenceMember([NotNullWhen(true)] SyntaxNode? node); private static bool IsDelegateInvoke(ISymbol symbol) { return symbol.Kind == SymbolKind.Method && ((IMethodSymbol)symbol).MethodKind == MethodKind.DelegateInvoke; } private static bool IsAnonymousDelegateInvoke(ISymbol symbol) { return IsDelegateInvoke(symbol) && symbol.ContainingType != null && symbol.ContainingType.IsAnonymousType(); } private bool ReplacementBreaksExpression(TExpressionSyntax expression, TExpressionSyntax newExpression) { var originalSymbolInfo = _semanticModel.GetSymbolInfo(expression); if (_failOnOverloadResolutionFailuresInOriginalCode && originalSymbolInfo.CandidateReason == CandidateReason.OverloadResolutionFailure) { return true; } var newSymbolInfo = this.SpeculativeSemanticModel.GetSymbolInfo(node: newExpression); var symbol = originalSymbolInfo.Symbol; var newSymbol = newSymbolInfo.Symbol; if (SymbolInfosAreCompatible(originalSymbolInfo, newSymbolInfo)) { // Original and new symbols for the invocation expression are compatible. // However, if the symbols are interface members and if the receiver symbol for one of the expressions is a possible ValueType type parameter, // and the other one is not, then there might be a boxing conversion at runtime which causes different runtime behavior. if (symbol.IsImplementableMember()) { if (IsReceiverNonUniquePossibleValueTypeParam(expression, this.OriginalSemanticModel) != IsReceiverNonUniquePossibleValueTypeParam(newExpression, this.SpeculativeSemanticModel)) { return true; } } return false; } if (symbol == null || newSymbol == null || originalSymbolInfo.CandidateReason != newSymbolInfo.CandidateReason) { return true; } if (newSymbol.IsOverride) { for (var overriddenMember = newSymbol.GetOverriddenMember(); overriddenMember != null; overriddenMember = overriddenMember.GetOverriddenMember()) { if (symbol.Equals(overriddenMember)) return !SymbolsHaveCompatibleParameterLists(symbol, newSymbol, expression); } } if (symbol.IsImplementableMember() && IsCompatibleInterfaceMemberImplementation( symbol, newSymbol, expression, newExpression, this.SpeculativeSemanticModel)) { return false; } // Allow speculated invocation expression to bind to a different method symbol if the method's containing type is a delegate type // which has a delegate variance conversion to/from the original method's containing delegate type. if (newSymbol.ContainingType.IsDelegateType() && symbol.ContainingType.IsDelegateType() && IsReferenceConversion(this.OriginalSemanticModel.Compilation, newSymbol.ContainingType, symbol.ContainingType)) { return false; } // Heuristic: If we now bind to an anonymous delegate's invoke method, assume that // this isn't a change in overload resolution. if (IsAnonymousDelegateInvoke(newSymbol)) { return false; } return true; } protected bool ReplacementBreaksCompoundAssignment( TExpressionSyntax originalLeft, TExpressionSyntax originalRight, TExpressionSyntax newLeft, TExpressionSyntax newRight) { var originalTargetType = this.OriginalSemanticModel.GetTypeInfo(originalLeft).Type; if (originalTargetType != null) { var newTargetType = this.SpeculativeSemanticModel.GetTypeInfo(newLeft).Type; return !SymbolsAreCompatible(originalTargetType, newTargetType) || !ImplicitConversionsAreCompatible(originalRight, originalTargetType, newRight, newTargetType!); } return false; } protected abstract bool IsReferenceConversion(Compilation model, ITypeSymbol sourceType, ITypeSymbol targetType); private bool IsCompatibleInterfaceMemberImplementation( ISymbol symbol, ISymbol newSymbol, TExpressionSyntax originalExpression, TExpressionSyntax newExpression, SemanticModel speculativeSemanticModel) { // In general, we don't want to remove casts to interfaces. It may have subtle changes in behavior, // especially if the types in question change in the future. For example, if a type becomes non-sealed or a // new interface impl is introduced, we may subtly break things. // // The only cases where we feel confident enough to elide the cast are: // // 1. When we have an Array/Delegate/Enum. These are such core types, and cannot be changed by teh user, // that we can trust their impls to not change. // 2. We have one of the builtin structs (like int). These are such core types, and cannot be changed by teh // user, that we can trust their impls to not change. // 3. if we have a struct and we know we have a fresh copy of it. In that case, boxing the struct to the // interface doesn't serve any purpose. var newSymbolContainingType = newSymbol.ContainingType; if (newSymbolContainingType == null) return false; var newReceiver = GetReceiver(newExpression); var newReceiverType = newReceiver != null ? speculativeSemanticModel.GetTypeInfo(newReceiver).ConvertedType : newSymbolContainingType; if (newReceiverType == null) return false; var implementationMember = newSymbolContainingType.FindImplementationForInterfaceMember(symbol); if (implementationMember == null) return false; if (!newSymbol.Equals(implementationMember)) return false; if (!SymbolsHaveCompatibleParameterLists(symbol, implementationMember, originalExpression)) return false; if (newReceiverType.IsValueType) { // Presume builtin value types are all immutable, and thus will have the same semantics when you call // interface members on them directly instead of through a boxed copy. if (newReceiverType.SpecialType != SpecialType.None) return true; // For non-builtins, only remove the boxing if we know we have a copy already. return newReceiver != null && IsReceiverUniqueInstance(newReceiver, speculativeSemanticModel); } return newSymbolContainingType.SpecialType is SpecialType.System_Array or SpecialType.System_Delegate or SpecialType.System_Enum or SpecialType.System_String; } private bool IsReceiverNonUniquePossibleValueTypeParam(TExpressionSyntax invocation, SemanticModel semanticModel) { var receiver = GetReceiver(invocation); if (receiver != null) { var receiverType = semanticModel.GetTypeInfo(receiver).Type; if (receiverType.IsKind(SymbolKind.TypeParameter) && !receiverType.IsReferenceType) { return !IsReceiverUniqueInstance(receiver, semanticModel); } } return false; } // Returns true if the given receiver expression for an invocation represents a unique copy of the underlying // object that is not referenced by any other variable. For example, if the receiver expression is produced by a // method call, property, or indexer, then it will be a fresh receiver in the case of value types. private static bool IsReceiverUniqueInstance(TExpressionSyntax receiver, SemanticModel semanticModel) { var receiverSymbol = semanticModel.GetSymbolInfo(receiver).GetAnySymbol(); if (receiverSymbol == null) return false; return receiverSymbol.IsKind(SymbolKind.Method) || receiverSymbol.IsIndexer() || receiverSymbol.IsKind(SymbolKind.Property); } protected abstract ImmutableArray<TArgumentSyntax> GetArguments(TExpressionSyntax expression); protected abstract TExpressionSyntax GetReceiver(TExpressionSyntax expression); private bool SymbolsHaveCompatibleParameterLists(ISymbol originalSymbol, ISymbol newSymbol, TExpressionSyntax originalInvocation) { if (originalSymbol.IsKind(SymbolKind.Method) || originalSymbol.IsIndexer()) { var specifiedArguments = GetArguments(originalInvocation); if (!specifiedArguments.IsDefault) { var symbolParameters = originalSymbol.GetParameters(); var newSymbolParameters = newSymbol.GetParameters(); return AreCompatibleParameterLists(specifiedArguments, symbolParameters, newSymbolParameters); } } return true; } protected abstract bool IsNamedArgument(TArgumentSyntax argument); protected abstract string GetNamedArgumentIdentifierValueText(TArgumentSyntax argument); private bool AreCompatibleParameterLists( ImmutableArray<TArgumentSyntax> specifiedArguments, ImmutableArray<IParameterSymbol> signature1Parameters, ImmutableArray<IParameterSymbol> signature2Parameters) { Debug.Assert(signature1Parameters.Length == signature2Parameters.Length); Debug.Assert(specifiedArguments.Length <= signature1Parameters.Length || (signature1Parameters.Length > 0 && !signature1Parameters.Last().IsParams)); if (signature1Parameters.Length != signature2Parameters.Length) { return false; } // If there aren't any parameters, we're OK. if (signature1Parameters.Length == 0) { return true; } // To ensure that the second parameter list is called in the same way as the // first, we need to use the specified arguments to bail out if... // // * A named argument doesn't have a corresponding parameter in the // in either parameter list, or... // // * A named argument matches a parameter that is in a different position // in the two parameter lists. // // After checking the specified arguments, we walk the unspecified parameters // in both parameter lists to ensure that they have matching default values. var specifiedParameters1 = new List<IParameterSymbol>(); var specifiedParameters2 = new List<IParameterSymbol>(); for (var i = 0; i < specifiedArguments.Length; i++) { var argument = specifiedArguments[i]; // Handle named argument if (IsNamedArgument(argument)) { var name = GetNamedArgumentIdentifierValueText(argument); var parameter1 = signature1Parameters.FirstOrDefault(p => p.Name == name); RoslynDebug.AssertNotNull(parameter1); var parameter2 = signature2Parameters.FirstOrDefault(p => p.Name == name); if (parameter2 == null) { return false; } if (signature1Parameters.IndexOf(parameter1) != signature2Parameters.IndexOf(parameter2)) { return false; } specifiedParameters1.Add(parameter1); specifiedParameters2.Add(parameter2); } else { // otherwise, treat the argument positionally, taking care to properly // handle params parameters. if (i < signature1Parameters.Length) { specifiedParameters1.Add(signature1Parameters[i]); specifiedParameters2.Add(signature2Parameters[i]); } } } // At this point, we can safely assume that specifiedParameters1 and signature2Parameters // contain parameters that appear at the same positions in their respective signatures // because we bailed out if named arguments referred to parameters at different positions. // // Now we walk the unspecified parameters to ensure that they have the same default // values. for (var i = 0; i < signature1Parameters.Length; i++) { var parameter1 = signature1Parameters[i]; if (specifiedParameters1.Contains(parameter1)) { continue; } var parameter2 = signature2Parameters[i]; Debug.Assert(parameter1.HasExplicitDefaultValue, "Expected all unspecified parameter to have default values"); Debug.Assert(parameter1.HasExplicitDefaultValue == parameter2.HasExplicitDefaultValue); if (parameter1.HasExplicitDefaultValue && parameter2.HasExplicitDefaultValue) { if (!object.Equals(parameter2.ExplicitDefaultValue, parameter1.ExplicitDefaultValue)) { return false; } if (object.Equals(parameter1.ExplicitDefaultValue, 0.0)) { RoslynDebug.Assert(object.Equals(parameter2.ExplicitDefaultValue, 0.0)); var isParam1DefaultValueNegativeZero = double.IsNegativeInfinity(1.0 / (double)parameter1.ExplicitDefaultValue); var isParam2DefaultValueNegativeZero = double.IsNegativeInfinity(1.0 / (double)parameter2.ExplicitDefaultValue); if (isParam1DefaultValueNegativeZero != isParam2DefaultValueNegativeZero) { return false; } } } } return true; } protected void GetConversions( TExpressionSyntax originalExpression, ITypeSymbol originalTargetType, TExpressionSyntax newExpression, ITypeSymbol newTargetType, out TConversion? originalConversion, out TConversion? newConversion) { originalConversion = null; newConversion = null; if (this.OriginalSemanticModel.GetTypeInfo(originalExpression).Type != null && this.SpeculativeSemanticModel.GetTypeInfo(newExpression).Type != null) { originalConversion = ClassifyConversion(this.OriginalSemanticModel, originalExpression, originalTargetType); newConversion = ClassifyConversion(this.SpeculativeSemanticModel, newExpression, newTargetType); } else { var originalConvertedTypeSymbol = this.OriginalSemanticModel.GetTypeInfo(originalExpression).ConvertedType; if (originalConvertedTypeSymbol != null) { originalConversion = ClassifyConversion(this.OriginalSemanticModel, originalConvertedTypeSymbol, originalTargetType); } var newConvertedTypeSymbol = this.SpeculativeSemanticModel.GetTypeInfo(newExpression).ConvertedType; if (newConvertedTypeSymbol != null) { newConversion = ClassifyConversion(this.SpeculativeSemanticModel, newConvertedTypeSymbol, newTargetType); } } } protected abstract TConversion ClassifyConversion(SemanticModel model, TExpressionSyntax expression, ITypeSymbol targetType); protected abstract TConversion ClassifyConversion(SemanticModel model, ITypeSymbol originalType, ITypeSymbol targetType); } }
49.700092
238
0.649526
[ "MIT" ]
GitHubPang/roslyn
src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/AbstractSpeculationAnalyzer.cs
54,026
C#
using System; using System.Reflection; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("AWSSDK.Core")] #if BCL35 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - Core Runtime")] #elif BCL45 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (4.5) - Core Runtime")] #elif PCL [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (PCL)- Core Runtime")] #elif UNITY [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (Unity)- Core Runtime")] #elif NETSTANDARD13 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (NetStandard 1.3)- Core Runtime")] #elif NETSTANDARD20 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (NetStandard 2.0)- Core Runtime")] #else #error Unknown platform constant - unable to set correct AssemblyDescription #endif [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("Amazon Web Services SDK for .NET")] [assembly: AssemblyCompany("Amazon.com, Inc")] [assembly: AssemblyCopyright("Copyright 2009-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("3.3")] [assembly: AssemblyFileVersion("3.3.104.5")] #if WINDOWS_PHONE || UNITY [assembly: System.CLSCompliant(false)] # else [assembly: System.CLSCompliant(true)] #endif #if BCL [assembly: System.Security.AllowPartiallyTrustedCallers] #endif #if BCL45 // Setting SecurityRules to level 1 to match .NET 2.0 rules and allow the // Amazon.Util.Settings.UserCrypto methods to work in .NET 4.5 [assembly: System.Security.SecurityRules(System.Security.SecurityRuleSet.Level1)] #endif //declare the permission we use in the manifest #if __ANDROID__ //network permission [assembly: Android.App.UsesPermission(Name="android.permission.INTERNET")] //for network reachability [assembly: Android.App.UsesPermission(Name="android.permission.ACCESS_NETWORK_STATE")] [assembly: Android.App.UsesPermission(Name="android.permission.ACCESS_WIFI_STATE")] //for storage [assembly: Android.App.UsesPermission(Name="android.permission.READ_EXTERNAL_STORAGE")] [assembly: Android.App.UsesPermission(Name="android.permission.WRITE_EXTERNAL_STORAGE")] #endif
37.851852
109
0.770385
[ "Apache-2.0" ]
gnurg/aws-sdk-net
sdk/src/Core/Properties/AssemblyInfo.cs
3,066
C#
// Copyright © 2017-2020 Chromely Projects. All rights reserved. // Use of this source code is governed by Chromely MIT licensed and CefSharp BSD-style license that can be found in the LICENSE file. using CefSharp; using CefSharp.Handler; using Chromely.Core.Configuration; using Chromely.Core.Network; namespace Chromely.CefSharp.Browser { public class DefaultRequestHandler : RequestHandler { public static readonly string VersionNumberString = $"Chromium: {Cef.ChromiumVersion}, CEF: {Cef.CefVersion}, CefSharp: {Cef.CefSharpVersion}"; protected readonly IChromelyConfiguration _config; protected readonly IChromelyRequestSchemeHandlerProvider _requestSchemeHandlerProvider; protected readonly IResourceRequestHandler _resourceRequestHandler; protected readonly IChromelyCommandTaskRunner _commandTaskRunner; public DefaultRequestHandler(IChromelyConfiguration config, IChromelyRequestSchemeHandlerProvider requestSchemeHandlerProvider, IResourceRequestHandler resourceRequestHandler, IChromelyCommandTaskRunner commandTaskRunner) { _config = config; _requestSchemeHandlerProvider = requestSchemeHandlerProvider; _resourceRequestHandler = resourceRequestHandler; _commandTaskRunner = commandTaskRunner; } protected override bool OnBeforeBrowse(IWebBrowser ChromiumBrowser, IBrowser browser, IFrame frame, IRequest request, bool userGesture, bool isRedirect) { var isUrlExternal = _config?.UrlSchemes?.IsUrlRegisteredExternalBrowserScheme(request.Url); if (isUrlExternal.HasValue && isUrlExternal.Value) { BrowserLauncher.Open(request.Url); return true; } var isUrlCommand = _config?.UrlSchemes?.IsUrlRegisteredCommandScheme(request.Url); if (isUrlCommand.HasValue && isUrlCommand.Value) { _commandTaskRunner.RunAsync(request.Url); return true; } return false; } protected override IResourceRequestHandler GetResourceRequestHandler(IWebBrowser ChromiumBrowser, IBrowser browser, IFrame frame, IRequest request, bool isNavigation, bool isDownload, string requestInitiator, ref bool disableDefaultHandling) { if (_requestSchemeHandlerProvider.IsSchemeRegistered(request.Url)) { return _resourceRequestHandler; } return null; } } public class DefaultResourceRequestHandler : ResourceRequestHandler { protected readonly IChromelyRequestSchemeHandlerProvider _requestSchemeHandlerProvider; public DefaultResourceRequestHandler(IChromelyRequestSchemeHandlerProvider requestSchemeHandlerProvider) { _requestSchemeHandlerProvider = requestSchemeHandlerProvider; } protected override IResourceHandler GetResourceHandler(IWebBrowser ChromiumBrowser, IBrowser browser, IFrame frame, IRequest request) { return _requestSchemeHandlerProvider.GetHandler(request.Url); } } }
43.25
249
0.695771
[ "MIT" ]
GerHobbelt/Chromely.CefSharp
src/Chromely.CefSharp/Browser/Handlers/DefaultRequestHandler.cs
3,290
C#
using Xms.Core.Data; using Xms.Data.Import.Domain; namespace Xms.Data.Import.Data { /// <summary> /// 导入文件仓储 /// </summary> public class ImportFileRepository : DefaultRepository<ImportFile>, IImportFileRepository { public ImportFileRepository(IDbContext dbContext) : base(dbContext) { } } }
22.666667
92
0.655882
[ "MIT" ]
861191244/xms
Libraries/Data/Xms.Data.Import/Data/ImportFileRepository.cs
354
C#
using NeoCA.Application.Models.Authentication; using System.Threading.Tasks; namespace NeoCA.Application.Contracts.Identity { public interface IAuthenticationService { Task<AuthenticationResponse> AuthenticateAsync(AuthenticationRequest request); Task<RegistrationResponse> RegisterAsync(RegistrationRequest request); Task<RefreshTokenResponse> RefreshTokenAsync(RefreshTokenRequest request); Task<RevokeTokenResponse> RevokeToken(RevokeTokenRequest request); } }
36.428571
86
0.794118
[ "Apache-2.0" ]
NeoSOFT-Technologies/netcore-template
Content/src/Core/NeoCA.Application/Contracts/Identity/IAuthenticationService.cs
512
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.SecurityInsights.V20210401 { /// <summary> /// Represents an incident comment /// </summary> [AzureNativeResourceType("azure-native:securityinsights/v20210401:IncidentComment")] public partial class IncidentComment : Pulumi.CustomResource { /// <summary> /// Describes the client that created the comment /// </summary> [Output("author")] public Output<Outputs.ClientInfoResponse> Author { get; private set; } = null!; /// <summary> /// The time the comment was created /// </summary> [Output("createdTimeUtc")] public Output<string> CreatedTimeUtc { get; private set; } = null!; /// <summary> /// Etag of the azure resource /// </summary> [Output("etag")] public Output<string?> Etag { get; private set; } = null!; /// <summary> /// The time the comment was updated /// </summary> [Output("lastModifiedTimeUtc")] public Output<string> LastModifiedTimeUtc { get; private set; } = null!; /// <summary> /// The comment message /// </summary> [Output("message")] public Output<string> Message { get; private set; } = null!; /// <summary> /// Azure resource name /// </summary> [Output("name")] public Output<string> Name { get; private set; } = null!; /// <summary> /// Azure Resource Manager metadata containing createdBy and modifiedBy information. /// </summary> [Output("systemData")] public Output<Outputs.SystemDataResponse> SystemData { get; private set; } = null!; /// <summary> /// Azure resource type /// </summary> [Output("type")] public Output<string> Type { get; private set; } = null!; /// <summary> /// Create a IncidentComment resource with the given unique name, arguments, and options. /// </summary> /// /// <param name="name">The unique name of the resource</param> /// <param name="args">The arguments used to populate this resource's properties</param> /// <param name="options">A bag of options that control this resource's behavior</param> public IncidentComment(string name, IncidentCommentArgs args, CustomResourceOptions? options = null) : base("azure-native:securityinsights/v20210401:IncidentComment", name, args ?? new IncidentCommentArgs(), MakeResourceOptions(options, "")) { } private IncidentComment(string name, Input<string> id, CustomResourceOptions? options = null) : base("azure-native:securityinsights/v20210401:IncidentComment", name, null, MakeResourceOptions(options, id)) { } private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id) { var defaultOptions = new CustomResourceOptions { Version = Utilities.Version, Aliases = { new Pulumi.Alias { Type = "azure-nextgen:securityinsights/v20210401:IncidentComment"}, new Pulumi.Alias { Type = "azure-native:securityinsights:IncidentComment"}, new Pulumi.Alias { Type = "azure-nextgen:securityinsights:IncidentComment"}, new Pulumi.Alias { Type = "azure-native:securityinsights/v20190101preview:IncidentComment"}, new Pulumi.Alias { Type = "azure-nextgen:securityinsights/v20190101preview:IncidentComment"}, new Pulumi.Alias { Type = "azure-native:securityinsights/v20210301preview:IncidentComment"}, new Pulumi.Alias { Type = "azure-nextgen:securityinsights/v20210301preview:IncidentComment"}, }, }; var merged = CustomResourceOptions.Merge(defaultOptions, options); // Override the ID if one was specified for consistency with other language SDKs. merged.Id = id ?? merged.Id; return merged; } /// <summary> /// Get an existing IncidentComment resource's state with the given name, ID, and optional extra /// properties used to qualify the lookup. /// </summary> /// /// <param name="name">The unique name of the resulting resource.</param> /// <param name="id">The unique provider ID of the resource to lookup.</param> /// <param name="options">A bag of options that control this resource's behavior</param> public static IncidentComment Get(string name, Input<string> id, CustomResourceOptions? options = null) { return new IncidentComment(name, id, options); } } public sealed class IncidentCommentArgs : Pulumi.ResourceArgs { /// <summary> /// Etag of the azure resource /// </summary> [Input("etag")] public Input<string>? Etag { get; set; } /// <summary> /// Incident comment ID /// </summary> [Input("incidentCommentId")] public Input<string>? IncidentCommentId { get; set; } /// <summary> /// Incident ID /// </summary> [Input("incidentId", required: true)] public Input<string> IncidentId { get; set; } = null!; /// <summary> /// The comment message /// </summary> [Input("message", required: true)] public Input<string> Message { get; set; } = null!; /// <summary> /// The name of the resource group within the user's subscription. The name is case insensitive. /// </summary> [Input("resourceGroupName", required: true)] public Input<string> ResourceGroupName { get; set; } = null!; /// <summary> /// The name of the workspace. /// </summary> [Input("workspaceName", required: true)] public Input<string> WorkspaceName { get; set; } = null!; public IncidentCommentArgs() { } } }
39.746914
152
0.597453
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/SecurityInsights/V20210401/IncidentComment.cs
6,439
C#
namespace MsCoreOne.Application.Common.Models { public class PaginationFilter { public int PageNumber { get; set; } public int PageSize { get; set; } public PaginationFilter() { this.PageNumber = 1; this.PageSize = 10; } public PaginationFilter(int pageNumber, int pageSize) { this.PageNumber = pageNumber < 1 ? 1 : pageNumber; this.PageSize = pageSize > 10 ? 10 : pageSize; } } }
23.136364
62
0.552063
[ "MIT" ]
jillmnolan/MsCoreOne
src/MsCoreOne.Application/Common/Models/PaginationFilter.cs
511
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerMovement : MonoBehaviour { public float moveSpeed; public Rigidbody2D mRigidbody; public List<Animator> characterPartsAnim = new List<Animator>(); public Vector2 movementDirection; private void Update() { if (GrandMaChatOrder.isChatOn) { return; } movementDirection.x = Input.GetAxisRaw("Horizontal"); movementDirection.y = Input.GetAxisRaw("Vertical"); foreach (Animator animator in characterPartsAnim) { animator.SetFloat("Horizontal", movementDirection.x); animator.SetFloat("Vertical", movementDirection.y); animator.SetFloat("Speed", movementDirection.magnitude); } } private void FixedUpdate() { if (GrandMaChatOrder.isChatOn) { return; } mRigidbody.MovePosition(mRigidbody.position + movementDirection * moveSpeed * Time.fixedDeltaTime); } public void findAndAddAnimators(string tag, List<Animator> animator) { foreach (var item in GameObject.FindGameObjectsWithTag(tag)) { animator.Add(item.GetComponent<Animator>()); }; } private void Awake() { findAndAddAnimators("characterParts", characterPartsAnim); } }
26.169811
107
0.642394
[ "MIT" ]
Afamuefuna/Shop-Trade-Game
Assets/Scripts/PlayerMovement.cs
1,387
C#
using System.Collections; using UnityEngine; /** * This component spawns the given object at fixed time-intervals at its object position. */ public class TimedSpawner: MonoBehaviour { [SerializeField] Mover prefabToSpawn; [SerializeField] Vector3 velocityOfSpawnedObject; [SerializeField] float timeBetweenSpawns = 1f; void Start() { this.StartCoroutine(SpawnRoutine()); Debug.Log("Start finished"); } private IEnumerator SpawnRoutine() { while (true) { GameObject newObject = Instantiate(prefabToSpawn.gameObject, transform.position, Quaternion.identity); newObject.GetComponent<Mover>().SetVelocity(velocityOfSpawnedObject); yield return new WaitForSeconds(timeBetweenSpawns); } } }
31.48
114
0.701398
[ "MIT" ]
Development-of-computer-games/Elad---Assignment-4---SpaceShip
Assets/Scripts/2-spawners/TimedSpawner.cs
789
C#
/** * Copyright 2013 Canada Health Infoway, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Author: $LastChangedBy: gng $ * Last modified: $LastChangedDate: 2015-11-19 18:20:12 -0500 (Fri, 30 Jan 2015) $ * Revision: $LastChangedRevision: 9755 $ */ /* This class was auto-generated by the message builder generator tools. */ using Ca.Infoway.Messagebuilder; namespace Ca.Infoway.Messagebuilder.Model.Ab_r02_04_03_shr.Domainvalue { public interface MedicalDeviceType : Code { } }
36.310345
83
0.709402
[ "ECL-2.0", "Apache-2.0" ]
CanadaHealthInfoway/message-builder-dotnet
message-builder-release-ab_r02_04_03_shr/Main/Ca/Infoway/Messagebuilder/Model/Ab_r02_04_03_shr/Domainvalue/MedicalDeviceType.cs
1,053
C#
using EventEmitter.Storage.POCO; namespace EventEmitter.Storage.Repositories.Linq2DbRepositories { public class PhoneRepository : Repository<Phone>, IPhoneRepository { } }
23
70
0.782609
[ "MIT" ]
Stelmashenko-A/EventEmitter
EventEmitter.Storage/Repositories/Linq2DbRepositories/PhoneRepository.cs
184
C#
using System; using System.IO; using System.Linq; using System.Text; using LibGit2Sharp.Tests.TestHelpers; using Xunit; namespace LibGit2Sharp.Tests { public class RepositoryOptionsFixture : BaseFixture { private readonly string newWorkdir; private readonly string newIndex; //TODO: Add facts ensuring the correct opening of a workdir/index through relative and absolute paths public RepositoryOptionsFixture() { SelfCleaningDirectory scd = BuildSelfCleaningDirectory(); newWorkdir = Path.Combine(scd.DirectoryPath, "wd"); Directory.CreateDirectory(newWorkdir); newIndex = Path.Combine(scd.DirectoryPath, "my-index"); } [Fact] public void CanOpenABareRepoAsIfItWasAStandardOne() { File.Copy(Path.Combine(StandardTestRepoPath, "index"), newIndex); var options = new RepositoryOptions { WorkingDirectoryPath = newWorkdir, IndexPath = newIndex }; string path = SandboxBareTestRepo(); using (var repo = new Repository(path, options)) { var st = repo.RetrieveStatus("1/branch_file.txt"); Assert.Equal(FileStatus.DeletedFromWorkdir, st); } } [Fact] public void CanOpenABareRepoAsIfItWasAStandardOneWithANonExisitingIndexFile() { var options = new RepositoryOptions { WorkingDirectoryPath = newWorkdir, IndexPath = newIndex }; string path = SandboxBareTestRepo(); using (var repo = new Repository(path, options)) { var st = repo.RetrieveStatus("1/branch_file.txt"); Assert.Equal(FileStatus.DeletedFromIndex, st); } } [Fact] public void CanOpenABareRepoWithOptions() { var options = new RepositoryOptions { GlobalConfigurationLocation = null }; string path = SandboxBareTestRepo(); using (var repo = new Repository(path, options)) { Assert.True(repo.Info.IsBare); } } [Fact] public void CanProvideADifferentWorkDirToAStandardRepo() { var path1 = SandboxStandardTestRepo(); using (var repo = new Repository(path1)) { Assert.Equal(FileStatus.Unaltered, repo.RetrieveStatus("1/branch_file.txt")); } var options = new RepositoryOptions { WorkingDirectoryPath = newWorkdir }; var path2 = SandboxStandardTestRepo(); using (var repo = new Repository(path2, options)) { Assert.Equal(FileStatus.DeletedFromWorkdir, repo.RetrieveStatus("1/branch_file.txt")); } } [Fact] public void CanProvideADifferentIndexToAStandardRepo() { var path1 = SandboxStandardTestRepo(); using (var repo = new Repository(path1)) { Assert.Equal(FileStatus.NewInWorkdir, repo.RetrieveStatus("new_untracked_file.txt")); repo.Stage("new_untracked_file.txt"); Assert.Equal(FileStatus.NewInIndex, repo.RetrieveStatus("new_untracked_file.txt")); File.Copy(Path.Combine(repo.Info.Path, "index"), newIndex); } var options = new RepositoryOptions { IndexPath = newIndex }; var path2 = SandboxStandardTestRepo(); using (var repo = new Repository(path2, options)) { Assert.Equal(FileStatus.NewInIndex, repo.RetrieveStatus("new_untracked_file.txt")); } } [Fact] public void OpeningABareRepoWithoutProvidingBothWorkDirAndIndexThrows() { string path = SandboxBareTestRepo(); Assert.Throws<ArgumentException>(() => new Repository(path, new RepositoryOptions {IndexPath = newIndex})); Assert.Throws<ArgumentException>(() => new Repository(path, new RepositoryOptions {WorkingDirectoryPath = newWorkdir})); } [Fact] public void CanSneakAdditionalCommitsIntoAStandardRepoWithoutAlteringTheWorkdirOrTheIndex() { string path = SandboxStandardTestRepo(); using (var repo = new Repository(path)) { Branch head = repo.Head; Assert.Equal(FileStatus.Nonexistent, repo.RetrieveStatus("zomg.txt")); string commitSha = MeanwhileInAnotherDimensionAnEvilMastermindIsAtWork(path); Branch newHead = repo.Head; Assert.NotEqual(head.Tip.Sha, newHead.Tip.Sha); Assert.Equal(commitSha, newHead.Tip.Sha); Assert.Equal(FileStatus.DeletedFromIndex, repo.RetrieveStatus("zomg.txt")); } } private string MeanwhileInAnotherDimensionAnEvilMastermindIsAtWork(string workingDirectoryPath) { var options = new RepositoryOptions { WorkingDirectoryPath = newWorkdir, IndexPath = newIndex }; using (var sneakyRepo = new Repository(workingDirectoryPath, options)) { Assert.Equal(Path.GetFullPath(newWorkdir) + Path.DirectorySeparatorChar, Path.GetFullPath(sneakyRepo.Info.WorkingDirectory)); sneakyRepo.Reset(ResetMode.Mixed, sneakyRepo.Head.Tip.Sha); const string filename = "zomg.txt"; Touch(sneakyRepo.Info.WorkingDirectory, filename, "I'm being sneaked in!\n"); sneakyRepo.Stage(filename); return sneakyRepo.Commit("Tadaaaa!", Constants.Signature, Constants.Signature).Sha; } } [Fact] public void CanProvideDifferentConfigurationFilesToARepository() { string globalLocation = Path.Combine(newWorkdir, "my-global-config"); string xdgLocation = Path.Combine(newWorkdir, "my-xdg-config"); string systemLocation = Path.Combine(newWorkdir, "my-system-config"); const string name = "Adam 'aroben' Roben"; const string email = "adam@github.com"; StringBuilder sb = new StringBuilder() .AppendLine("[user]") .AppendFormat("name = {0}{1}", name, Environment.NewLine) .AppendFormat("email = {0}{1}", email, Environment.NewLine); File.WriteAllText(globalLocation, sb.ToString()); File.WriteAllText(systemLocation, string.Empty); File.WriteAllText(xdgLocation, string.Empty); var options = new RepositoryOptions { GlobalConfigurationLocation = globalLocation, XdgConfigurationLocation = xdgLocation, SystemConfigurationLocation = systemLocation, }; string path = SandboxBareTestRepo(); using (var repo = new Repository(path, options)) { Assert.True(repo.Config.HasConfig(ConfigurationLevel.Global)); Assert.Equal(name, repo.Config.Get<string>("user.name").Value); Assert.Equal(email, repo.Config.Get<string>("user.email").Value); repo.Config.Set("xdg.setting", "https://twitter.com/libgit2sharp", ConfigurationLevel.Xdg); repo.Config.Set("help.link", "https://twitter.com/xpaulbettsx/status/205761932626636800", ConfigurationLevel.System); } AssertValueInConfigFile(systemLocation, "xpaulbettsx"); } [Fact] public void CanCommitOnBareRepository() { string repoPath = InitNewRepository(true); SelfCleaningDirectory scd = BuildSelfCleaningDirectory(); string workPath = Path.Combine(scd.RootedDirectoryPath, "work"); Directory.CreateDirectory(workPath); var repositoryOptions = new RepositoryOptions { WorkingDirectoryPath = workPath, IndexPath = Path.Combine(scd.RootedDirectoryPath, "index") }; using (var repo = new Repository(repoPath, repositoryOptions)) { const string relativeFilepath = "test.txt"; Touch(repo.Info.WorkingDirectory, relativeFilepath, "test\n"); repo.Stage(relativeFilepath); Assert.NotNull(repo.Commit("Initial commit", Constants.Signature, Constants.Signature)); Assert.Equal(1, repo.Head.Commits.Count()); Assert.Equal(1, repo.Commits.Count()); } } } }
38.738739
141
0.606744
[ "MIT" ]
AArnott/libgit2sharp
LibGit2Sharp.Tests/RepositoryOptionsFixture.cs
8,602
C#
//----------------------------------------------------------------------- // <copyright file="CosmosElementType.cs" company="Microsoft Corporation"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //----------------------------------------------------------------------- namespace Microsoft.Azure.Cosmos.CosmosElements { internal enum CosmosElementType { Array, Boolean, Null, Number, Object, String, Guid, Binary, } }
27.842105
74
0.436673
[ "MIT" ]
JohnLTaylor/azure-cosmos-dotnet-v3
Microsoft.Azure.Cosmos/src/CosmosElements/CosmosElementType.cs
531
C#
using System.Collections.Generic; using RimWorld; using Verse; using Verse.AI; namespace Brrr; public class JobDriver_BrrrRecovery : JobDriver { public const TargetIndex BedOrRestSpotIndex = TargetIndex.A; public Building_Bed Bed => (Building_Bed)job.GetTarget(TargetIndex.A).Thing; public override bool TryMakePreToilReservations(bool errorOnFailed) { if (!job.GetTarget(TargetIndex.A).HasThing) { return true; } var localPawn = pawn; LocalTargetInfo target = Bed; var localJob = job; var sleepingSlotsCount = Bed.SleepingSlotsCount; var stackCount = 0; if (!localPawn.Reserve(target, localJob, sleepingSlotsCount, stackCount, null, errorOnFailed)) { return false; } return true; } public override bool CanBeginNowWhileLyingDown() { return JobInBedUtility.InBedOrRestSpotNow(pawn, job.GetTarget(TargetIndex.A)); } protected override IEnumerable<Toil> MakeNewToils() { var hasBed = job.GetTarget(TargetIndex.A).HasThing; if (hasBed) { yield return Toils_Bed.ClaimBedIfNonMedical(TargetIndex.A); yield return Toils_Bed.GotoBed(TargetIndex.A); } else { yield return Toils_Goto.GotoCell(TargetIndex.A, PathEndMode.OnCell); } yield return Toils_BrrrLayDown.BrrrLayDown(TargetIndex.A, hasBed); } public override string GetReport() { if (asleep) { return "Brrr.BrrrRecoverSleeping".Translate(); } return "Brrr.BrrrRecoverResting".Translate(); } }
26.234375
102
0.63788
[ "MIT" ]
emipa606/BrrandPhew
Source/Brrr/JobDriver_BrrrRecovery.cs
1,679
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class StrengthenWonder : AbstractWonder { private bool isPraying = false; private bool isPrayEffectActive = false; public override void Update() { base.UpdateWonder(); } protected override void OnStartWonder() { } protected override void OnEndWonder() { } protected override void OnStartWonderEffect() { Debug.Log("Start strengthen"); foreach (GoodGuyAI goodGuy in FindObjectsOfType<GoodGuyAI>()) { goodGuy.StartStrengthen(); } } protected override void OnEndWonderEffect() { Debug.Log("End strengthen"); foreach (GoodGuyAI goodGuy in FindObjectsOfType<GoodGuyAI>()) { goodGuy.EndStrengthen(); } } }
22.375
70
0.602235
[ "Unlicense" ]
NTrixner/CultWars
Assets/Scripts/Wonders/StrengthenWonder.cs
897
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the gamelift-2015-10-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.GameLift.Model { /// <summary> /// Container for the parameters to the CreateGameSessionQueue operation. /// Establishes a new queue for processing requests to place new game sessions. A queue /// identifies where new game sessions can be hosted -- by specifying a list of destinations /// (fleets or aliases) -- and how long requests can wait in the queue before timing out. /// You can set up a queue to try to place game sessions on fleets in multiple Regions. /// To add placement requests to a queue, call <a>StartGameSessionPlacement</a> and reference /// the queue name. /// /// /// <para> /// <b>Destination order.</b> When processing a request for a game session, Amazon GameLift /// tries each destination in order until it finds one with available resources to host /// the new game session. A queue's default order is determined by how destinations are /// listed. The default order is overridden when a game session placement request provides /// player latency information. Player latency information enables Amazon GameLift to /// prioritize destinations where players report the lowest average latency, as a result /// placing the new game session where the majority of players will have the best possible /// gameplay experience. /// </para> /// /// <para> /// <b>Player latency policies.</b> For placement requests containing player latency /// information, use player latency policies to protect individual players from very high /// latencies. With a latency cap, even when a destination can deliver a low latency for /// most players, the game is not placed where any individual player is reporting latency /// higher than a policy's maximum. A queue can have multiple latency policies, which /// are enforced consecutively starting with the policy with the lowest latency cap. Use /// multiple policies to gradually relax latency controls; for example, you might set /// a policy with a low latency cap for the first 60 seconds, a second policy with a higher /// cap for the next 60 seconds, etc. /// </para> /// /// <para> /// To create a new queue, provide a name, timeout value, a list of destinations and, /// if desired, a set of latency policies. If successful, a new queue object is returned. /// </para> /// /// <para> /// <b>Learn more</b> /// </para> /// /// <para> /// <a href="https://docs.aws.amazon.com/gamelift/latest/developerguide/queues-design.html"> /// Design a Game Session Queue</a> /// </para> /// /// <para> /// <a href="https://docs.aws.amazon.com/gamelift/latest/developerguide/queues-creating.html"> /// Create a Game Session Queue</a> /// </para> /// /// <para> /// <b>Related operations</b> /// </para> /// <ul> <li> /// <para> /// <a>CreateGameSessionQueue</a> /// </para> /// </li> <li> /// <para> /// <a>DescribeGameSessionQueues</a> /// </para> /// </li> <li> /// <para> /// <a>UpdateGameSessionQueue</a> /// </para> /// </li> <li> /// <para> /// <a>DeleteGameSessionQueue</a> /// </para> /// </li> </ul> /// </summary> public partial class CreateGameSessionQueueRequest : AmazonGameLiftRequest { private List<GameSessionQueueDestination> _destinations = new List<GameSessionQueueDestination>(); private string _name; private List<PlayerLatencyPolicy> _playerLatencyPolicies = new List<PlayerLatencyPolicy>(); private List<Tag> _tags = new List<Tag>(); private int? _timeoutInSeconds; /// <summary> /// Gets and sets the property Destinations. /// <para> /// A list of fleets that can be used to fulfill game session placement requests in the /// queue. Fleets are identified by either a fleet ARN or a fleet alias ARN. Destinations /// are listed in default preference order. /// </para> /// </summary> public List<GameSessionQueueDestination> Destinations { get { return this._destinations; } set { this._destinations = value; } } // Check to see if Destinations property is set internal bool IsSetDestinations() { return this._destinations != null && this._destinations.Count > 0; } /// <summary> /// Gets and sets the property Name. /// <para> /// A descriptive label that is associated with game session queue. Queue names must be /// unique within each Region. /// </para> /// </summary> [AWSProperty(Required=true, Min=1, Max=128)] public string Name { get { return this._name; } set { this._name = value; } } // Check to see if Name property is set internal bool IsSetName() { return this._name != null; } /// <summary> /// Gets and sets the property PlayerLatencyPolicies. /// <para> /// A collection of latency policies to apply when processing game sessions placement /// requests with player latency information. Multiple policies are evaluated in order /// of the maximum latency value, starting with the lowest latency values. With just one /// policy, the policy is enforced at the start of the game session placement for the /// duration period. With multiple policies, each policy is enforced consecutively for /// its duration period. For example, a queue might enforce a 60-second policy followed /// by a 120-second policy, and then no policy for the remainder of the placement. A player /// latency policy must set a value for <code>MaximumIndividualPlayerLatencyMilliseconds</code>. /// If none is set, this API request fails. /// </para> /// </summary> public List<PlayerLatencyPolicy> PlayerLatencyPolicies { get { return this._playerLatencyPolicies; } set { this._playerLatencyPolicies = value; } } // Check to see if PlayerLatencyPolicies property is set internal bool IsSetPlayerLatencyPolicies() { return this._playerLatencyPolicies != null && this._playerLatencyPolicies.Count > 0; } /// <summary> /// Gets and sets the property Tags. /// <para> /// A list of labels to assign to the new game session queue resource. Tags are developer-defined /// key-value pairs. Tagging AWS resources are useful for resource management, access /// management and cost allocation. For more information, see <a href="https://docs.aws.amazon.com/general/latest/gr/aws_tagging.html"> /// Tagging AWS Resources</a> in the <i>AWS General Reference</i>. Once the resource is /// created, you can use <a>TagResource</a>, <a>UntagResource</a>, and <a>ListTagsForResource</a> /// to add, remove, and view tags. The maximum tag limit may be lower than stated. See /// the AWS General Reference for actual tagging limits. /// </para> /// </summary> [AWSProperty(Min=0, Max=200)] public List<Tag> Tags { get { return this._tags; } set { this._tags = value; } } // Check to see if Tags property is set internal bool IsSetTags() { return this._tags != null && this._tags.Count > 0; } /// <summary> /// Gets and sets the property TimeoutInSeconds. /// <para> /// The maximum time, in seconds, that a new game session placement request remains in /// the queue. When a request exceeds this time, the game session placement changes to /// a <code>TIMED_OUT</code> status. /// </para> /// </summary> [AWSProperty(Min=0)] public int TimeoutInSeconds { get { return this._timeoutInSeconds.GetValueOrDefault(); } set { this._timeoutInSeconds = value; } } // Check to see if TimeoutInSeconds property is set internal bool IsSetTimeoutInSeconds() { return this._timeoutInSeconds.HasValue; } } }
41.431111
143
0.629157
[ "Apache-2.0" ]
PureKrome/aws-sdk-net
sdk/src/Services/GameLift/Generated/Model/CreateGameSessionQueueRequest.cs
9,322
C#
using CSharpSpeed; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using static InstrumentedLibrary.Maths; using static System.Math; namespace InstrumentedLibrary { /// <summary> /// The wrap angle tests class. /// </summary> [DisplayName("Wrap Angle Tests")] [Description("Reduces a given angle to a value between 2π and -2π.")] [SourceCodeLocationProvider] public static class WrapAngleTests { /// <summary> /// Set of tests to run testing methods that calculate the wrapped angle of an angle. /// </summary> /// <returns></returns> [DisplayName(nameof(WrapAngleTests))] public static List<SpeedTester> TestHarness() { var trials = 100000; var tests = new Dictionary<object[], TestCaseResults> { { new object[] { 480d.ToRadians() }, new TestCaseResults(description: "An angle that wraps more than 360 degrees.", trials: trials, expectedReturnValue:-4.1887902047863914d, epsilon: double.Epsilon) }, { new object[] { 45d.ToRadians() }, new TestCaseResults(description: "An angle that wraps less than 360 degrees.", trials: trials, expectedReturnValue:-5.497787143782138d, epsilon: double.Epsilon) }, }; var results = new List<SpeedTester>(); foreach (var method in HelperExtensions.ListStaticMethodsWithAttribute(MethodBase.GetCurrentMethod().DeclaringType, typeof(SourceCodeLocationProviderAttribute))) { var methodDescription = ((DescriptionAttribute)method.GetCustomAttribute(typeof(DescriptionAttribute)))?.Description; results.Add(new SpeedTester(method, methodDescription, tests)); } return results; } /// <summary> /// /// </summary> /// <param name="angle"></param> /// <returns></returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] [Signature] public static double WrapAngle(this double angle) => WrapAngle00(angle); /// <summary> /// Reduces a given angle to a value between 2π and -2π. /// </summary> /// <param name="angle">The angle to reduce, in radians.</param> /// <returns>The new angle, in radians.</returns> [DisplayName("Wrap Angle 1")] [Description("Reduces a given angle to a value between 2π and -2π.")] [SourceCodeLocationProvider] [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static double WrapAngle00(double angle) { if (double.IsNaN(angle)) { return angle; } // The IEEERemainder method works better than the % modulus operator in this case, even if it is slower. //double value = IEEERemainder(angle, Tau); // The active ingredient of the IEEERemainder method is extracted here for performance reasons. var value = angle - (Tau * Round(angle * InverseTau)); return (value <= -PI) ? value + Tau : value - Tau; } /// <summary> /// Reduces a given angle to a value between π and -π. /// </summary> /// <param name="angle">The angle to reduce, in radians.</param> /// <returns>The new angle, in radians.</returns> [DisplayName("Wrap Angle 2")] [Description("Reduces a given angle to a value between 2π and -2π.")] [SourceCodeLocationProvider] [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static double WrapAngle0(double angle) { // The IEEERemainder method works better than the % modulus operator in this case, even if it is slower. var value = IEEERemainder(angle, Tau); return (value <= -PI) ? value + Tau : value - Tau; } /// <summary> /// Reduces a given angle to a value between 2π and -2π. /// </summary> /// <param name="angle">The angle to reduce, in radians.</param> /// <returns>The new angle, in radians.</returns> [DisplayName("Wrap Angle 3")] [Description("Reduces a given angle to a value between 2π and -2π.")] [SourceCodeLocationProvider] [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static double WrapAngle1(double angle) { // The active ingredient of the IEEERemainder method. var value = angle - (Tau * Round(angle * InverseTau)); return (value <= -PI) ? value + Tau : value - Tau; } /// <summary> /// Reduces a given angle to a value between π and -π. /// </summary> /// <param name="angle">The angle to reduce, in radians.</param> /// <returns>The new angle, in radians.</returns> [DisplayName("Wrap Angle 4")] [Description("Reduces a given angle to a value between 2π and -2π.")] [SourceCodeLocationProvider] [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static double WrapAngle2(double angle) { var test = IEEERemainder(angle, Tau); if (test <= -PI) { test += Tau; } else if (test > PI) { test -= Tau; } return test; } /// <summary> /// Reduces a given angle to a value between π and -π. /// </summary> /// <param name="angle">The angle to reduce, in radians.</param> /// <returns>The new angle, in radians.</returns> [DisplayName("Wrap Angle 5")] [Description("Reduces a given angle to a value between 2π and -2π.")] [SourceCodeLocationProvider] [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static double WrapAngle3(double angle) { var test = angle % Tau; return (test <= -PI) ? test + Tau : test - Tau; } } }
41.118421
217
0.59664
[ "MIT" ]
Shkyrockett/CSharpSpeed
InstrumentedLibrary/Mathmatics/Angles/WrapAngleTests.cs
6,274
C#
using System.Globalization; using IQFeed.CSharpApiClient.Extensions; namespace IQFeed.CSharpApiClient.Lookup.Symbol.Messages { public class ListedMarketMessage { public ListedMarketMessage(int listedMarketId, string shortName, string longName, int groupID, string shortGroupName, string requestId = null) { ListedMarketId = listedMarketId; ShortName = shortName; LongName = longName; GroupId = groupID; ShortGroupName = shortGroupName; RequestId = requestId; } public int ListedMarketId { get; private set; } public string ShortName { get; private set; } public string LongName { get; private set; } public int GroupId { get; private set; } public string ShortGroupName { get; private set; } public string RequestId { get; private set; } public static ListedMarketMessage Parse(string message) { var values = message.SplitFeedMessage(); return new ListedMarketMessage( int.Parse(values[0], CultureInfo.InvariantCulture), values[1], values[2], int.Parse(values[3], CultureInfo.InvariantCulture), values[4]); } public static ListedMarketMessage ParseWithRequestId(string message) { var values = message.SplitFeedMessage(); var requestId = values[0]; return new ListedMarketMessage( int.Parse(values[1], CultureInfo.InvariantCulture), values[2], values[3], int.Parse(values[4], CultureInfo.InvariantCulture), values[5], requestId); } public override bool Equals(object obj) { return obj is ListedMarketMessage message && RequestId == message.RequestId && ListedMarketId == message.ListedMarketId && ShortName == message.ShortName && LongName == message.LongName && GroupId == message.GroupId && ShortGroupName == message.ShortGroupName; } public override int GetHashCode() { unchecked { var hash = 17; hash = hash * 29 + RequestId != null ? RequestId.GetHashCode() : 0; hash = hash * 29 + ListedMarketId.GetHashCode(); hash = hash * 29 + ShortName.GetHashCode(); hash = hash * 29 + LongName.GetHashCode(); hash = hash * 29 + GroupId.GetHashCode(); hash = hash * 29 + ShortGroupName.GetHashCode(); return hash; } } public override string ToString() { return $"{nameof(ListedMarketId)}: {ListedMarketId}, {nameof(ShortName)}: {ShortName}, {nameof(LongName)}: {LongName}, {nameof(GroupId)}: {GroupId}, {nameof(ShortGroupName)}: {ShortGroupName}, {nameof(RequestId)}: {RequestId}"; } } }
38.04878
239
0.557372
[ "MIT" ]
BunkerCoder/IQFeed.CSharpApiClient
src/IQFeed.CSharpApiClient/Lookup/Symbol/Messages/ListedMarketMessage.cs
3,122
C#
namespace HostfileManager.ViewModel { using System; using System.IO; using HostfileManager.Logic; using HostfileManager.Model; using HostfileManager.Model.Base; using HostfileManager.View; /// <summary> /// The ViewModel class for the <see cref="EditorView"/> user-interface. /// </summary> public class HostsFileViewModel : ViewModelBase { #region private members /// <summary>The <see cref="HostFile"/> object for this view.</summary> private HostFile hostFileInstance; /// <summary> /// A flag indicating wehther this object has been disposed. /// </summary> private bool disposed; #endregion #region constructor(s) /// <summary>Initializes a new instance of the <see cref="HostsFileViewModel"/> class.</summary> public HostsFileViewModel() { /* attach content-changed event */ HostfileManager.Current.HostFileContentChanged += this.HostsFileContentChanged; } #endregion #region public events /// <summary>Event that is raised when the <see cref="HostFileInstance"/> property changed.</summary> public event EventHandler<EventArgs> HostsFileObjectChanged; #endregion #region public properties /// <summary> /// Gets or sets the <see cref="HostFile"/> for this ViewModel. /// </summary> public HostFile HostFileInstance { get { return this.hostFileInstance ?? (this.hostFileInstance = HostfileManager.Current.GetHostsFile()); } set { this.hostFileInstance = value; OnPropertyChanged(null); this.InvokeHostsFileObjectChanged(); } } #endregion #region public functions and methods /// <summary>Restores the default hosts-file content.</summary> /// <returns>True if the default hosts-file could be restored; otherwise false.</returns> public bool RestoreDefaultHostsFile() { bool result = HostfileManager.Current.RestoreDefaultHostsFile(); if (result) { this.ReloadFromDisk(); } return result; } /// <summary> /// Loads the specified <see cref="HostsFileProfile"/>. /// </summary> /// <param name="sourceProfile">A <see cref="HostsFileProfile"/> object.</param> /// <returns>True if the specified <paramref name="sourceProfile"/> was loaded successfully; otherwise false.</returns> public bool LoadProfile(HostsFileProfile sourceProfile) { if (this.HostFileInstance != null) { HostFile hf = HostfileManager.Current.GetProfile(sourceProfile.ProfilePath); if (hf != null) { this.HostFileInstance = hf; return true; } } return false; } /// <summary>Loads the hosts file with specified <paramref name="filePath"/>.</summary> /// <param name="filePath">The file path to a hosts file or a hosts file profile.</param> /// <returns>True if the specified <paramref name="filePath"/> was loaded successfully; otherwise false.</returns> public bool LoadFile(string filePath) { if (string.IsNullOrEmpty(filePath)) { throw new ArgumentNullException("filePath"); } if (this.HostFileInstance != null) { HostFile hf = HostfileManager.Current.GetHostsFile(filePath); if (hf != null) { this.HostFileInstance = hf; return true; } } return false; } /// <summary> /// Save the current <see cref="HostFileInstance"/> back to the current user's hosts file. /// </summary> /// <returns>True if the data was successfully exported and saved; otherwise false.</returns> public bool SaveToDisk() { return this.SaveToDisk(this.HostFileInstance.FilePath); } /// <summary>Save the current <see cref="HostFileInstance"/> back to the current user's hosts file.</summary> /// <param name="filepath">The filepath.</param> /// <returns>True if the data was successfully exported and saved; otherwise false.</returns> public bool SaveToDisk(string filepath) { this.HostFileInstance.FilePath = filepath; bool result = HostfileManager.Current.SaveHostsFileContent(this.HostFileInstance, filepath); if (result) { this.InvokeHostsFileObjectChanged(); } return result; } /// <summary>Save the specified <paramref name="text"/> back to the current user's hosts file.</summary> /// <param name="filepath">The filepath.</param> /// <param name="text">The new hosts file content.</param> /// <returns>True if the specified <paramref name="text"/> was successfully saved; otherwise false.</returns> public bool SaveToDisk(string filepath, string text) { if (text != null) { this.HostFileInstance.FilePath = filepath; if (HostfileManager.Current.SaveHostsFileContent(text, filepath)) { this.ReloadFromDisk(filepath); } else { return false; } } return false; } /// <summary>Reloads the content of the hosts file from disk and updates the user-interface.</summary> public void ReloadFromDisk() { this.ReloadFromDisk(this.HostFileInstance.FilePath); } /// <summary>Reloads the content of the supplied hosts file from disk and updates the user-interface.</summary> /// <param name="filepath">The full path to a hosts file or a hosts file profile.</param> public void ReloadFromDisk(string filepath) { FileInfo fileInfo = new FileInfo(filepath); this.HostsFileContentChanged(this, new FileSystemEventArgs(WatcherChangeTypes.Changed, fileInfo.Directory.FullName, fileInfo.Name)); } /// <summary>Gets the text-representation of the current <see cref="HostFileInstance"/>.</summary> /// <returns>The text-representation of the current <see cref="HostFileInstance"/>.</returns> public string GetText() { return HostfileManager.Current.ConvertHostfileToText(this.HostFileInstance); } /// <summary>Raises the <see cref="HostsFileObjectChanged"/> event.</summary> public void InvokeHostsFileObjectChanged() { this.InvokeHostsFileObjectChanged(EventArgs.Empty); } /// <summary>Raises the <see cref="HostsFileObjectChanged"/> event.</summary> /// <param name="e">The <see cref="EventArgs"/> event parameter object.</param> public void InvokeHostsFileObjectChanged(EventArgs e) { EventHandler<EventArgs> handler = this.HostsFileObjectChanged; if (handler != null) { handler(this, e); } } /// <summary>Toggle the active state of the specified <paramref name="activatableHostfileEntry"/>.</summary> /// <param name="activatableHostfileEntry">A <see cref="IHostfileEntry"/> object.</param> /// <returns>True if the active state of the specified <see cref="IHostfileEntry"/> was successfully toggled; otherwise false.</returns> public bool ToggleActiveState(ActivatableHostfileEntry activatableHostfileEntry) { /* abort if parameter is null */ if (activatableHostfileEntry == null) { return false; } /* toggle host status */ if (activatableHostfileEntry.HasParent) { activatableHostfileEntry.ToggleActiveState(); return true; } /* toggle group status */ return this.HostFileInstance.ToggleActiveState(activatableHostfileEntry.UniqueIdentifier); } /// <summary>Remove all <see cref="IHostfileEntry"/> objects from the current <see cref="HostFileInstance"/>.</summary> /// <returns>True if the all <see cref="IHostfileEntry"/> objects have been removed from the current <see cref="HostFileInstance"/>; otherwise false.</returns> public bool Clear() { return this.HostFileInstance != null && this.HostFileInstance.Clear(); } /// <summary>Remove the specified <paramref name="hostfileEntry"/>.</summary> /// <param name="hostfileEntry">A <see cref="IHostfileEntry"/> object.</param> /// <returns>True if the specified <paramref name="hostfileEntry"/> was successfully removed; otherwise false.</returns> public bool Remove(IHostfileEntry hostfileEntry) { if (hostfileEntry != null) { if (hostfileEntry.HasParent) { hostfileEntry.Delete(); } else { this.HostFileInstance.Remove(hostfileEntry.UniqueIdentifier); } } return false; } /// <summary> /// Move the specified <paramref name="hostfileEntry"/> up. /// </summary> /// <param name="hostfileEntry">A <see cref="IHostfileEntry"/> object.</param> /// <returns>True if the specified <paramref name="hostfileEntry"/> was successfully moved up; otherwise false.</returns> public bool MoveUp(IHostfileEntry hostfileEntry) { if (hostfileEntry != null) { if (hostfileEntry.HasParent) { hostfileEntry.MoveUp(); } else { this.HostFileInstance.MoveUp(hostfileEntry.UniqueIdentifier); } } return false; } /// <summary> /// Move the specified <paramref name="hostfileEntry"/> down. /// </summary> /// <param name="hostfileEntry">A <see cref="IHostfileEntry"/> object.</param> /// <returns>True if the specified <paramref name="hostfileEntry"/> was successfully moved down; otherwise false.</returns> public bool MoveDown(IHostfileEntry hostfileEntry) { if (hostfileEntry != null) { if (hostfileEntry.HasParent) { hostfileEntry.MoveDown(); } else { this.HostFileInstance.MoveDown(hostfileEntry.UniqueIdentifier); } } return false; } /// <summary>Add an empty <see cref="Comment"/> object instance to the current <see cref="HostFileInstance"/>.</summary> /// <returns>True if a new <see cref="Comment"/> object instance has been successfully added to the current <see cref="HostFileInstance"/>; otherwise false.</returns> public bool AddComment() { return this.HostFileInstance != null && this.HostFileInstance.AddChildToTop(Comment.CreateEmpty(this.HostFileInstance.PropertyChangedCallBack)); } /// <summary>Add an empty <see cref="HostGroup"/> object instance to the current <see cref="HostFileInstance"/>.</summary> /// <returns>True if a new <see cref="HostGroup"/> object instance has been successfully added to the current <see cref="HostFileInstance"/>; otherwise false.</returns> public bool AddGroup() { return this.HostFileInstance != null && this.HostFileInstance.AddChildToTop(HostGroup.CreateEmpty(this.HostFileInstance.PropertyChangedCallBack)); } /// <summary>Add an empty <see cref="Host"/> object instance to the current <see cref="HostFileInstance"/>.</summary> /// <param name="parent">The parent of the to be created <see cref="Host"/> object (optional, default = null).</param> /// <returns>True if a new <see cref="Host"/> object instance has been successfully added to the current <see cref="HostFileInstance"/>; otherwise false.</returns> public bool AddHost(HostGroup parent = null) { if (this.HostFileInstance != null) { if (parent != null) { return parent.AddChildToTop(Host.CreateEmpty(parent, this.HostFileInstance.PropertyChangedCallBack)); } return this.HostFileInstance.AddChildToTop(Host.CreateEmpty(parent, this.HostFileInstance.PropertyChangedCallBack)); } return false; } /// <summary>Add an empty <see cref="Domain"/> object instance to the current <see cref="HostFileInstance"/>.</summary> /// <param name="parent">The parent of the to be created <see cref="Domain"/> object (optional, default = null).</param> /// <returns>True if a new <see cref="Domain"/> object instance has been successfully added to the current <see cref="HostFileInstance"/>; otherwise false.</returns> public bool AddDomain(Host parent) { if (parent != null && this.HostFileInstance != null) { return parent.AddChildToTop(Domain.CreateEmpty(parent, this.HostFileInstance.PropertyChangedCallBack)); } return false; } #endregion #region IDisposable members /// <summary>Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.</summary> /// <param name="disposing">A flag indicating whether this object is currently disposing.</param> protected override void Dispose(bool disposing) { if (this.disposed == false) { if (disposing) { this.hostFileInstance = null; HostfileManager.Current.Dispose(); } // Free your own state (unmanaged objects). // Set large fields to null. this.disposed = true; } base.Dispose(disposing); } #endregion #region private function, methods and events /// <summary> /// Updates the user-interface with the values from the new hosts-file content. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">An <see cref="FileSystemEventArgs"/> that contains the event data.</param> private void HostsFileContentChanged(object sender, FileSystemEventArgs e) { if (string.IsNullOrEmpty(e.FullPath) || File.Exists(e.FullPath) == false) { return; } HostFile newHostsFile = HostfileManager.Current.GetHostsFile(e.FullPath); if (newHostsFile != null) { /* attach new data-model */ this.HostFileInstance = newHostsFile; } } #endregion } }
39.930175
177
0.564951
[ "MIT" ]
andreaskoch/Hostfile-Manager
HostfileManager/ViewModel/HostsFileViewModel.cs
16,014
C#
using System.Collections.Generic; using Newtonsoft.Json; namespace GherkinSyncTool.Synchronizers.TestRail.Model { public class CaseCustomFields { [JsonProperty("custom_preconds")] public string Preconditions { get; init; } [JsonProperty("custom_steps_separated")] public List<CustomStepsSeparated> StepsSeparated { get; init; } [JsonProperty("custom_tags")] public string Tags { get; init; } [JsonProperty("custom_gherkinsynctool_id")] public string GherkinSyncToolId { get; init; } } }
28.9
71
0.67128
[ "Apache-2.0" ]
quantori/GherkinSyncTool
GherkinSyncTool.Synchronizers.TestRail/Model/CaseCustomFields.cs
580
C#
namespace ChatCode.Bot.Models { public sealed class CreateAboutMeModel { public string Email { get; set; } public string NameSurname { get; set; } public string Age { get; set; } public string Gender { get; set; } public string Description { get; set; } public string[] AnalysisText { get; set; } public string ImageUrl { get; set; } public string Background { get; set; } public string Foreground { get; set; } } }
23.043478
51
0.564151
[ "MIT" ]
onurcelikeng/ChatCode
ChatCode.Bot/Models/CreateAboutMeModel.cs
532
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Terminal.Gui; using static UICatalog.Scenario; namespace UICatalog.Scenarios { [ScenarioMetadata (Name: "Interactive Tree", Description: "Create nodes and child nodes in TreeView")] [ScenarioCategory ("Controls")] class InteractiveTree : Scenario { TreeView treeView; public override void Setup () { Win.Title = this.GetName (); Win.Y = 1; // menu Win.Height = Dim.Fill (1); // status bar Top.LayoutSubviews (); var menu = new MenuBar (new MenuBarItem [] { new MenuBarItem ("_File", new MenuItem [] { new MenuItem ("_Quit", "", () => Quit()), }) }); Top.Add (menu); treeView = new TreeView () { X = 0, Y = 0, Width = Dim.Fill (), Height = Dim.Fill (1), }; treeView.KeyPress += TreeView_KeyPress; Win.Add (treeView); var statusBar = new StatusBar (new StatusItem [] { new StatusItem(Key.CtrlMask | Key.Q, "~^Q~ Quit", () => Quit()), new StatusItem(Key.CtrlMask | Key.C, "~^C~ Add Child", () => AddChildNode()), new StatusItem(Key.CtrlMask | Key.T, "~^T~ Add Root", () => AddRootNode()), new StatusItem(Key.CtrlMask | Key.R, "~^R~ Rename Node", () => RenameNode()), }); Top.Add (statusBar); } private void TreeView_KeyPress (View.KeyEventEventArgs obj) { if (obj.KeyEvent.Key == Key.DeleteChar) { var toDelete = treeView.SelectedObject; if (toDelete == null) { return; } obj.Handled = true; // if it is a root object remove it if (treeView.Objects.Contains (toDelete)) { treeView.Remove (toDelete); } else { var parent = treeView.GetParent (toDelete); if (parent == null) { MessageBox.ErrorQuery ("Could not delete", $"Parent of '{toDelete}' was unexpectedly null", "Ok"); } else { //update the model parent.Children.Remove (toDelete); //refresh the tree treeView.RefreshObject (parent); } } } } private void RenameNode () { var node = treeView.SelectedObject; if (node != null) { if (GetText ("Text", "Enter text for node:", node.Text, out string entered)) { node.Text = entered; treeView.RefreshObject (node); } } } private void AddRootNode () { if (GetText ("Text", "Enter text for node:", "", out string entered)) { treeView.AddObject (new TreeNode (entered)); } } private void AddChildNode () { var node = treeView.SelectedObject; if (node != null) { if (GetText ("Text", "Enter text for node:", "", out string entered)) { node.Children.Add (new TreeNode (entered)); treeView.RefreshObject (node); } } } private bool GetText (string title, string label, string initialText, out string enteredText) { bool okPressed = false; var ok = new Button ("Ok", is_default: true); ok.Clicked += () => { okPressed = true; Application.RequestStop (); }; var cancel = new Button ("Cancel"); cancel.Clicked += () => { Application.RequestStop (); }; var d = new Dialog (title, 60, 20, ok, cancel); var lbl = new Label () { X = 0, Y = 1, Text = label }; var tf = new TextField () { Text = initialText, X = 0, Y = 2, Width = Dim.Fill () }; d.Add (lbl, tf); tf.SetFocus (); Application.Run (d); enteredText = okPressed ? tf.Text.ToString () : null; return okPressed; } private void Quit () { Application.RequestStop (); } } }
23.417219
104
0.605769
[ "MIT" ]
Zhou-zhi-peng/gui.cs
UICatalog/Scenarios/InteractiveTree.cs
3,538
C#
namespace Fixie.Tests.TestAdapter { using System; using System.Collections.Generic; using System.Threading.Tasks; using Fixie.TestAdapter; using Microsoft.VisualStudio.TestPlatform.ObjectModel; using Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter; using Microsoft.VisualStudio.TestPlatform.ObjectModel.Logging; using Assertions; using Reports; using static System.Environment; public class ExecutionReportTests : MessagingTests { public async Task ShouldMapMessagesToVsTestExecutionRecorder() { const string assemblyPath = "assembly.path.dll"; var recorder = new StubExecutionRecorder(); var report = new ExecutionReport(recorder, assemblyPath); var output = await Run(report); output.Console .ShouldBe( "Standard Out: Fail", "Standard Out: FailByAssertion", "Standard Out: Pass"); var messages = recorder.Messages; messages.Count.ShouldBe(13); foreach (var message in messages) { if (message is TestResult result) { result.Traits.ShouldBeEmpty(); result.Attachments.ShouldBeEmpty(); result.ComputerName.ShouldBe(MachineName); } } var failStart = (TestCase)messages[0]; var fail = (TestResult)messages[1]; var failByAssertionStart = (TestCase)messages[2]; var failByAssertion = (TestResult)messages[3]; var passStart = (TestCase)messages[4]; var pass = (TestResult)messages[5]; var skip = (TestResult)messages[6]; var shouldBeStringPassAStart = (TestCase)messages[7]; var shouldBeStringPassA = (TestResult)messages[8]; var shouldBeStringPassBStart = (TestCase)messages[9]; var shouldBeStringPassB = (TestResult)messages[10]; var shouldBeStringFailStart = (TestCase)messages[11]; var shouldBeStringFail = (TestResult)messages[12]; failStart.ShouldBeExecutionTimeTest(TestClass + ".Fail", assemblyPath); fail.TestCase.ShouldBeExecutionTimeTest(TestClass+".Fail", assemblyPath); fail.TestCase.DisplayName.ShouldBe(TestClass+".Fail"); fail.Outcome.ShouldBe(TestOutcome.Failed); fail.ErrorMessage.ShouldBe("'Fail' failed!"); fail.ErrorStackTrace .Lines() .NormalizeStackTraceLines() .ShouldBe("Fixie.Tests.FailureException", At("Fail()")); fail.DisplayName.ShouldBe(TestClass+".Fail"); fail.Messages.Count.ShouldBe(1); fail.Messages[0].Category.ShouldBe(TestResultMessage.StandardOutCategory); fail.Messages[0].Text.Lines().ShouldBe("Standard Out: Fail"); fail.Duration.ShouldBeGreaterThanOrEqualTo(TimeSpan.Zero); failByAssertionStart.ShouldBeExecutionTimeTest(TestClass + ".FailByAssertion", assemblyPath); failByAssertion.TestCase.ShouldBeExecutionTimeTest(TestClass+".FailByAssertion", assemblyPath); failByAssertion.TestCase.DisplayName.ShouldBe(TestClass+".FailByAssertion"); failByAssertion.Outcome.ShouldBe(TestOutcome.Failed); failByAssertion.ErrorMessage.Lines().ShouldBe( "Expected: 2", "Actual: 1"); failByAssertion.ErrorStackTrace .Lines() .NormalizeStackTraceLines() .ShouldBe("Fixie.Tests.Assertions.AssertException", At("FailByAssertion()")); failByAssertion.DisplayName.ShouldBe(TestClass+".FailByAssertion"); failByAssertion.Messages.Count.ShouldBe(1); failByAssertion.Messages[0].Category.ShouldBe(TestResultMessage.StandardOutCategory); failByAssertion.Messages[0].Text.Lines().ShouldBe("Standard Out: FailByAssertion"); failByAssertion.Duration.ShouldBeGreaterThanOrEqualTo(TimeSpan.Zero); passStart.ShouldBeExecutionTimeTest(TestClass + ".Pass", assemblyPath); pass.TestCase.ShouldBeExecutionTimeTest(TestClass+".Pass", assemblyPath); pass.TestCase.DisplayName.ShouldBe(TestClass+".Pass"); pass.Outcome.ShouldBe(TestOutcome.Passed); pass.ErrorMessage.ShouldBe(null); pass.ErrorStackTrace.ShouldBe(null); pass.DisplayName.ShouldBe(TestClass+".Pass"); pass.Messages.Count.ShouldBe(1); pass.Messages[0].Category.ShouldBe(TestResultMessage.StandardOutCategory); pass.Messages[0].Text.Lines().ShouldBe("Standard Out: Pass"); pass.Duration.ShouldBeGreaterThanOrEqualTo(TimeSpan.Zero); skip.TestCase.ShouldBeExecutionTimeTest(TestClass+".Skip", assemblyPath); skip.TestCase.DisplayName.ShouldBe(TestClass+".Skip"); skip.Outcome.ShouldBe(TestOutcome.Skipped); skip.ErrorMessage.ShouldBe("⚠ Skipped with attribute."); skip.ErrorStackTrace.ShouldBe(null); skip.DisplayName.ShouldBe(TestClass+".Skip"); skip.Messages.ShouldBeEmpty(); skip.Duration.ShouldBeGreaterThanOrEqualTo(TimeSpan.Zero); shouldBeStringPassAStart.ShouldBeExecutionTimeTest(GenericTestClass + ".ShouldBeString", assemblyPath); shouldBeStringPassA.TestCase.ShouldBeExecutionTimeTest(GenericTestClass+".ShouldBeString", assemblyPath); shouldBeStringPassA.TestCase.DisplayName.ShouldBe(GenericTestClass+".ShouldBeString"); shouldBeStringPassA.Outcome.ShouldBe(TestOutcome.Passed); shouldBeStringPassA.ErrorMessage.ShouldBe(null); shouldBeStringPassA.ErrorStackTrace.ShouldBe(null); shouldBeStringPassA.DisplayName.ShouldBe(GenericTestClass+".ShouldBeString<System.String>(\"A\")"); shouldBeStringPassA.Messages.ShouldBeEmpty(); shouldBeStringPassA.Duration.ShouldBeGreaterThanOrEqualTo(TimeSpan.Zero); shouldBeStringPassBStart.ShouldBeExecutionTimeTest(GenericTestClass + ".ShouldBeString", assemblyPath); shouldBeStringPassB.TestCase.ShouldBeExecutionTimeTest(GenericTestClass+".ShouldBeString", assemblyPath); shouldBeStringPassB.TestCase.DisplayName.ShouldBe(GenericTestClass+".ShouldBeString"); shouldBeStringPassB.Outcome.ShouldBe(TestOutcome.Passed); shouldBeStringPassB.ErrorMessage.ShouldBe(null); shouldBeStringPassB.ErrorStackTrace.ShouldBe(null); shouldBeStringPassB.DisplayName.ShouldBe(GenericTestClass+".ShouldBeString<System.String>(\"B\")"); shouldBeStringPassB.Messages.ShouldBeEmpty(); shouldBeStringPassB.Duration.ShouldBeGreaterThanOrEqualTo(TimeSpan.Zero); shouldBeStringFailStart.ShouldBeExecutionTimeTest(GenericTestClass + ".ShouldBeString", assemblyPath); shouldBeStringFail.TestCase.ShouldBeExecutionTimeTest(GenericTestClass+".ShouldBeString", assemblyPath); shouldBeStringFail.TestCase.DisplayName.ShouldBe(GenericTestClass+".ShouldBeString"); shouldBeStringFail.Outcome.ShouldBe(TestOutcome.Failed); shouldBeStringFail.ErrorMessage.Lines().ShouldBe( "Expected: System.String", "Actual: System.Int32"); shouldBeStringFail.ErrorStackTrace .Lines() .NormalizeStackTraceLines() .ShouldBe( "Fixie.Tests.Assertions.AssertException", At<SampleGenericTestClass>("ShouldBeString[T](T genericArgument)")); shouldBeStringFail.DisplayName.ShouldBe(GenericTestClass+".ShouldBeString<System.Int32>(123)"); shouldBeStringFail.Messages.ShouldBeEmpty(); shouldBeStringFail.Duration.ShouldBeGreaterThanOrEqualTo(TimeSpan.Zero); } class StubExecutionRecorder : ITestExecutionRecorder { public List<object> Messages { get; } = new List<object>(); public void RecordStart(TestCase testCase) => Messages.Add(testCase); public void RecordResult(TestResult testResult) => Messages.Add(testResult); public void SendMessage(TestMessageLevel testMessageLevel, string message) => throw new NotImplementedException(); public void RecordEnd(TestCase testCase, TestOutcome outcome) => throw new NotImplementedException(); public void RecordAttachments(IList<AttachmentSet> attachmentSets) => throw new NotImplementedException(); } } }
48.639344
117
0.654421
[ "MIT" ]
lpedras/fixie
src/Fixie.Tests/TestAdapter/ExecutionReportTests.cs
8,905
C#
#region license // Copyright (c) 2004, Rodrigo B. de Oliveira (rbo@acm.org) // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // * Neither the name of Rodrigo B. de Oliveira nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF // THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion using System; using Boo.Lang.Compiler.Ast; using Boo.Lang.Compiler.Services; using Boo.Lang.Compiler.TypeSystem; using Boo.Lang.Environments; using Boo.Lang.Resources; namespace Boo.Lang.Compiler { public static class CompilerWarningFactory { public static class Codes { public const string ImplicitReturn = "BCW0023"; public const string VisibleMemberDoesNotDeclareTypeExplicitely = "BCW0024"; public const string ImplicitDowncast = "BCW0028"; } public static CompilerWarning CustomWarning(Node node, string msg) { return CustomWarning(AstUtil.SafeLexicalInfo(node), msg); } public static CompilerWarning CustomWarning(LexicalInfo lexicalInfo, string msg) { return new CompilerWarning(lexicalInfo, msg); } public static CompilerWarning CustomWarning(string msg) { return new CompilerWarning(msg); } public static CompilerWarning AbstractMemberNotImplemented(Node node, IType type, IMember member) { return Instantiate("BCW0001", AstUtil.SafeLexicalInfo(node), type, member); } public static CompilerWarning ModifiersInLabelsHaveNoEffect(Node node) { return Instantiate("BCW0002", AstUtil.SafeLexicalInfo(node)); } public static CompilerWarning UnusedLocalVariable(Node node, string name) { return Instantiate("BCW0003", AstUtil.SafeLexicalInfo(node), name); } public static CompilerWarning IsInsteadOfIsa(Node node) { return Instantiate("BCW0004", AstUtil.SafeLexicalInfo(node), LanguageAmbiance.IsKeyword, LanguageAmbiance.IsaKeyword); } private static LanguageAmbiance LanguageAmbiance { get { return My<LanguageAmbiance>.Instance; } } public static CompilerWarning InvalidEventUnsubscribe(Node node, IEvent eventName, CallableSignature expected) { return Instantiate("BCW0005", AstUtil.SafeLexicalInfo(node), eventName, expected); } public static CompilerWarning AssignmentToTemporary(Node node) { return Instantiate("BCW0006", AstUtil.SafeLexicalInfo(node)); } public static CompilerWarning EqualsInsteadOfAssign(BinaryExpression node) { return Instantiate("BCW0007", AstUtil.SafeLexicalInfo(node), node.ToCodeString()); } public static CompilerWarning DuplicateNamespace(Import import, string name) { return Instantiate("BCW0008", AstUtil.SafeLexicalInfo(import.Expression), name); } public static CompilerWarning HaveBothKeyFileAndAttribute(Node node) { return Instantiate("BCW0009", AstUtil.SafeLexicalInfo(node)); } public static CompilerWarning HaveBothKeyNameAndAttribute(Node node) { return Instantiate("BCW0010", AstUtil.SafeLexicalInfo(node)); } public static CompilerWarning AbstractMemberNotImplementedStubCreated(Node node, IType type, IMember abstractMember) { return Instantiate("BCW0011", AstUtil.SafeLexicalInfo(node), type, abstractMember); } public static CompilerWarning Obsolete(Node node, IMember member, string message) { return Instantiate("BCW0012", AstUtil.SafeLexicalInfo(node), member, message); } public static CompilerWarning StaticClassMemberRedundantlyMarkedStatic(Node node, string typeName, string memberName) { return Instantiate("BCW0013", AstUtil.SafeLexicalInfo(node), typeName, memberName); } public static CompilerWarning PrivateMemberNeverUsed(TypeMember member) { return Instantiate("BCW0014", AstUtil.SafeLexicalInfo(member), MemberVisibilityString(member), NodeTypeString(member), member.FullName); } public static CompilerWarning UnreachableCodeDetected(Node node) { return Instantiate("BCW0015", AstUtil.SafeLexicalInfo(node)); } public static CompilerWarning NamespaceNeverUsed(Import node) { return Instantiate("BCW0016", AstUtil.SafeLexicalInfo(node.Expression), node.Expression.ToCodeString()); } public static CompilerWarning NewProtectedMemberInSealedType(TypeMember member) { return Instantiate("BCW0017", AstUtil.SafeLexicalInfo(member), NodeTypeString(member), member.Name, member.DeclaringType.Name); } public static CompilerWarning OverridingFinalizeIsBadPractice(TypeMember member) { return Instantiate("BCW0018", AstUtil.SafeLexicalInfo(member)); } public static CompilerWarning AmbiguousExceptionName(ExceptionHandler node) { return Instantiate("BCW0019", AstUtil.SafeLexicalInfo(node), node.Declaration.Name); } public static CompilerWarning AssignmentToSameVariable(BinaryExpression node) { return Instantiate("BCW0020", AstUtil.SafeLexicalInfo(node)); } public static CompilerWarning ComparisonWithSameVariable(BinaryExpression node) { return Instantiate("BCW0021", AstUtil.SafeLexicalInfo(node)); } public static CompilerWarning ConstantExpression(Expression node) { return Instantiate("BCW0022", AstUtil.SafeLexicalInfo(node)); } public static CompilerWarning ImplicitReturn(Method node) { return Instantiate(Codes.ImplicitReturn, AstUtil.SafeLexicalInfo(node)); } public static CompilerWarning VisibleMemberDoesNotDeclareTypeExplicitely(TypeMember node) { return VisibleMemberDoesNotDeclareTypeExplicitely(node, null); } public static CompilerWarning VisibleMemberDoesNotDeclareTypeExplicitely(TypeMember node, string argument) { string details = (null == argument) ? StringResources.BooC_Return : string.Format(StringResources.BooC_NamedArgument, argument); return Instantiate(Codes.VisibleMemberDoesNotDeclareTypeExplicitely, AstUtil.SafeLexicalInfo(node), NodeTypeString(node), details); } public static CompilerWarning AmbiguousVariableName(Local node, string localName, string baseName) { return Instantiate("BCW0025", AstUtil.SafeLexicalInfo(node), localName, baseName); } public static CompilerWarning LikelyTypoInTypeMemberName(TypeMember node, string suggestion) { return Instantiate("BCW0026", AstUtil.SafeLexicalInfo(node), node.Name, suggestion); } public static CompilerWarning ObsoleteSyntax(Node anchor, string obsoleteSyntax, string newSyntax) { return ObsoleteSyntax(AstUtil.SafeLexicalInfo(anchor), obsoleteSyntax, newSyntax); } public static CompilerWarning ObsoleteSyntax(LexicalInfo location, string obsoleteSyntax, string newSyntax) { return Instantiate("BCW0027", location, obsoleteSyntax, newSyntax); } public static CompilerWarning ImplicitDowncast(Node node, IType expectedType, IType actualType) { return Instantiate(Codes.ImplicitDowncast, AstUtil.SafeLexicalInfo(node), actualType, expectedType); } public static CompilerWarning MethodHidesInheritedNonVirtual(Node anchor, IMethod hidingMethod, IMethod hiddenMethod) { return Instantiate("BCW0029", AstUtil.SafeLexicalInfo(anchor), hidingMethod, hiddenMethod); } public static CompilerWarning AsyncNoAwait(Method anchor) { return Instantiate("BCW0030", AstUtil.SafeLexicalInfo(anchor)); } public static CompilerWarning IconNotFound(string filename) { return Instantiate("BCW0031", LexicalInfo.Empty, filename); } private static CompilerWarning Instantiate(string code, LexicalInfo location, params object[] args) { return new CompilerWarning(code, location, Array.ConvertAll<object, string>(args, CompilerErrorFactory.DisplayStringFor)); } private static string NodeTypeString(Node node) { return node.NodeType.ToString().ToLower(); } private static string MemberVisibilityString(TypeMember member) { switch (member.Modifiers & TypeMemberModifiers.VisibilityMask) { case TypeMemberModifiers.Private: return "Private"; case TypeMemberModifiers.Internal: return "Internal"; case TypeMemberModifiers.Protected: return "Protected"; } return "Public"; } } }
36.850575
140
0.750988
[ "BSD-3-Clause" ]
Code-distancing/boo
src/Boo.Lang.Compiler/CompilerWarningFactory.cs
9,618
C#
using System; using FubuMVC.Core.Registration; using FubuMVC.Core.Registration.Nodes; using FubuMVC.Core.Registration.ObjectGraph; using NUnit.Framework; using FubuCore; using System.Linq; using FubuTestingSupport; namespace FubuMVC.Tests.Registration { [TestFixture] public class ServiceGraphTester { private ServiceGraph theGraph; private ITracedModel theTracedNode; [SetUp] public void SetUp() { theGraph = new ServiceGraph(); theTracedNode = theGraph.As<ITracedModel>(); } public class Something { public Something() { Message = string.Empty; } public string Message { get; set; } } [Test] public void configure_is_idempotent() { var graph = new ServiceGraph(); graph.Configure<Something>(m => m.Message += "a"); graph.Configure<Something>(m => m.Message += "b"); graph.Configure<Something>(m => m.Message += "c"); graph.Configure<Something>(m => m.Message += "d"); graph.Configure<Something>(m => m.Message += "e"); graph.FindAllValues<Something>().Single().Message.ShouldEqual("abcde"); } [Test] public void adding_a_service_registers_a_service_added_event() { theGraph.AddService(typeof(IFoo), new ObjectDef(typeof(Foo))); var added = theTracedNode.StagedEvents.Last().ShouldBeOfType<ServiceAdded>(); added.ServiceType.ShouldEqual(typeof (IFoo)); added.Def.Type.ShouldEqual(typeof (Foo)); } [Test] public void clear_registers_service_removed_events() { theGraph.AddService(typeof(IFoo), new ObjectDef(typeof(Foo))); theGraph.AddService(typeof(IFoo), new ObjectDef(typeof(Foo2))); theGraph.AddService(typeof(IFoo), new ObjectDef(typeof(Foo3))); theGraph.AddService(typeof(IFoo), new ObjectDef(typeof(Foo4))); theGraph.Clear(typeof(IFoo)); theTracedNode.StagedEvents.OfType<ServiceRemoved>().Where(x => x.ServiceType == typeof(IFoo)) .Select(x => x.Def.Type) .ShouldHaveTheSameElementsAs(typeof(Foo), typeof(Foo2), typeof(Foo3), typeof(Foo4)); } [Test] public void has_any() { theGraph.HasAny(typeof(IFoo)).ShouldBeFalse(); theGraph.AddService(typeof(IFoo), ObjectDef.ForType<Foo>()); theGraph.HasAny(typeof(IFoo)).ShouldBeTrue(); } [Test] public void fill_type() { theGraph.AddService(typeof(IFoo), ObjectDef.ForType<Foo>()); theGraph.FillType(typeof(IFoo), typeof(Foo)); theGraph.FillType(typeof(IFoo), typeof(Foo)); theGraph.FillType(typeof(IFoo), typeof(Foo)); theGraph.FillType(typeof(IFoo), typeof(Foo)); theGraph.ServicesFor(typeof (IFoo)).Count().ShouldEqual(1); theGraph.FillType(typeof(IFoo), typeof(Foo2)); theGraph.ServicesFor(typeof (IFoo)).Select(x => x.Type) .ShouldHaveTheSameElementsAs(typeof(Foo), typeof(Foo2)); } public interface IFoo{} public class Foo : IFoo{} public class Foo2 : IFoo{} public class Foo3 : IFoo{} public class Foo4 : IFoo{} } }
32.752294
106
0.570028
[ "Apache-2.0" ]
DovetailSoftware/fubumvc
src/FubuMVC.Tests/Registration/ServiceGraphTester.cs
3,570
C#
using System; using System.Linq; using System.Reflection; namespace BenchmarkLogGenerator.Utilities { public static class ExtendedType { public static FieldInfo[] GetFieldsOrdered(this Type type) { return type.GetFields().OrderBy(fi => fi.MetadataToken).ToArray(); } public static Type GetTypeWithNullableSupport(this Type type) { if (type.Name.StartsWith("Nullable")) { var declaredFields = ((TypeInfo)type).DeclaredFields; var valueFieldInfo = declaredFields.Where(fi => string.Equals(fi.Name, "value", StringComparison.OrdinalIgnoreCase)).FirstOrDefault(); return (valueFieldInfo != default(FieldInfo)) ? valueFieldInfo.FieldType : type; } return type; } } }
30.785714
151
0.603248
[ "MIT" ]
hau-mal/TelemetryLogsGeneratorAndBenchmark
Utilities/ExtendedType.cs
864
C#
using System; using System.Collections; using System.Collections.Generic; // The class UserCases.Calls contains (as static members) transparent methods to be used // as calls at the base of a SxS stack in SameStackHost2 tests. To select method Foo from // this file, the first argument to SameStackHost2 should be: UserCases_Calls_Foo. class Calls { static int Return100() { Console.WriteLine("Returning 100..."); return 100; } static int ThrowManaged() { Console.WriteLine("Throwing managed exception.."); throw new NotSupportedException("blagh"); return 100; } static int InterfaceThrow() { Console.WriteLine("Interface call to null object"); Array a = null; IList<int> l = (IList<int>)a; l.Clear(); return 100; } }
26.419355
89
0.665446
[ "MIT" ]
CyberSys/coreclr-mono
tests/src/hosting/coreclr/activation/sxshost/usercases.cs
819
C#
/* * Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0) * See https://github.com/KastraCMS/kastra-core for more information concerning * the license and the contributors participating to this project. */ using System.Reflection; using System.Threading.Tasks; namespace Kastra.Core.Services.Contracts { public interface IModuleManager { /// <summary> /// Installs the modules present in the folder modules. /// </summary> Task InstallModulesAsync(); /// <summary> /// Uninstalls the modules. /// </summary> Task UninstallModulesAsync(); /// <summary> /// Installs the module. /// </summary> /// <param name="assembly">Assembly.</param> Task InstallModuleAsync(Assembly assembly); /// <summary> /// Uninstalls the module. /// </summary> /// <param name="assembly">Assembly.</param> Task UninstallModuleAsync(Assembly assembly); } }
28.75
94
0.619324
[ "Apache-2.0" ]
KastraCMS/kastra-core
src/Kastra.Core/Services/Contracts/IModuleManager.cs
1,035
C#
/* Copyright 2017 YANG Huan (sy.yanghuan@gmail.com). Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics.Contracts; using System.Linq; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis; using CSharpLua.LuaAst; namespace CSharpLua { public sealed partial class LuaSyntaxNodeTransform : CSharpSyntaxVisitor<LuaSyntaxNode> { public const int kStringConstInlineCount = 27; private sealed class MethodInfo { public IMethodSymbol Symbol { get; } public IList<LuaExpressionSyntax> RefOrOutParameters { get; } public List<LuaIdentifierNameSyntax> InliningReturnVars { get; set; } public bool IsInlining => InliningReturnVars != null; public bool HasYield; public MethodInfo(IMethodSymbol symbol) { Symbol = symbol; RefOrOutParameters = Array.Empty<LuaExpressionSyntax>(); } public MethodInfo(IMethodSymbol symbol, IList<LuaExpressionSyntax> refOrOutParameters) { Symbol = symbol; RefOrOutParameters = refOrOutParameters; } } internal sealed class TypeDeclarationInfo { public INamedTypeSymbol TypeSymbol { get; } public LuaTypeDeclarationSyntax TypeDeclaration { get; } public TypeDeclarationInfo(INamedTypeSymbol typeSymbol, LuaTypeDeclarationSyntax luaTypeDeclarationSyntax) { TypeSymbol = typeSymbol; TypeDeclaration = luaTypeDeclarationSyntax; } public bool CheckTypeName(INamedTypeSymbol getNameTypeSymbol, out LuaIdentifierNameSyntax name) { if (getNameTypeSymbol.EQ(TypeSymbol)) { TypeDeclaration.IsClassUsed = true; name = LuaIdentifierNameSyntax.Class; return true; } name = null; return false; } } private readonly LuaSyntaxGenerator generator_; private SemanticModel semanticModel_; private readonly Stack<LuaCompilationUnitSyntax> compilationUnits_ = new Stack<LuaCompilationUnitSyntax>(); private readonly Stack<TypeDeclarationInfo> typeDeclarations_ = new Stack<TypeDeclarationInfo>(); private readonly Stack<LuaFunctionExpressionSyntax> functions_ = new Stack<LuaFunctionExpressionSyntax>(); private readonly Stack<MethodInfo> methodInfos_ = new Stack<MethodInfo>(); private readonly Stack<LuaBlockSyntax> blocks_ = new Stack<LuaBlockSyntax>(); private readonly Stack<LuaIfStatementSyntax> ifStatements_ = new Stack<LuaIfStatementSyntax>(); private readonly Stack<LuaSwitchAdapterStatementSyntax> switchs_ = new Stack<LuaSwitchAdapterStatementSyntax>(); private int releaseTempIdentifierCount_; private int noImportTypeNameCounter_; public bool IsNoImportTypeName => noImportTypeNameCounter_ > 0; private int genericTypeCounter_; public bool IsNoneGenericTypeCounter => genericTypeCounter_ == 0; public void AddGenericTypeCounter() => ++genericTypeCounter_; public void SubGenericTypeCounter() => --genericTypeCounter_; private int metadataTypeNameCounter_; public bool IsMetadataTypeName => metadataTypeNameCounter_ > 0; private static readonly Dictionary<string, string> operatorTokenMapps_ = new Dictionary<string, string>() { ["!="] = LuaSyntaxNode.Tokens.NotEquals, ["!"] = LuaSyntaxNode.Tokens.Not, ["&&"] = LuaSyntaxNode.Tokens.And, ["||"] = LuaSyntaxNode.Tokens.Or, ["??"] = LuaSyntaxNode.Tokens.Or, ["^"] = LuaSyntaxNode.Tokens.BitXor, }; public LuaSyntaxNodeTransform(LuaSyntaxGenerator generator, SemanticModel semanticModel) { generator_ = generator; semanticModel_ = semanticModel; } private XmlMetaProvider XmlMetaProvider { get { return generator_.XmlMetaProvider; } } private static string GetOperatorToken(SyntaxToken operatorToken) { string token = operatorToken.ValueText; return GetOperatorToken(token); } private static string GetOperatorToken(string token) { return operatorTokenMapps_.GetOrDefault(token, token); } private bool IsLuaClassic => generator_.Setting.IsClassic; private bool IsLuaNewest => !IsLuaClassic; private bool IsPreventDebug => generator_.Setting.IsPreventDebugObject; private LuaCompilationUnitSyntax CurCompilationUnit { get { return compilationUnits_.Peek(); } } private LuaTypeDeclarationSyntax CurType { get { return typeDeclarations_.Peek().TypeDeclaration; } } private INamedTypeSymbol CurTypeSymbol { get { return typeDeclarations_.Peek().TypeSymbol; } } internal TypeDeclarationInfo CurTypeDeclaration { get { return typeDeclarations_.Count > 0 ? typeDeclarations_.Peek() : null; } } private LuaFunctionExpressionSyntax CurFunction { get { return functions_.Peek(); } } private LuaFunctionExpressionSyntax CurFunctionOrNull { get { return functions_.Count > 0 ? functions_.Peek() : null; } } private MethodInfo CurMethodInfoOrNull { get { return methodInfos_.Count > 0 ? methodInfos_.Peek() : null; } } private void PushFunction(LuaFunctionExpressionSyntax function) { functions_.Push(function); ++localMappingCounter_; PushBlock(function.Body); } private void PopFunction() { PopBlock(); var fucntion = functions_.Pop(); --localMappingCounter_; if (localMappingCounter_ == 0) { localReservedNames_.Clear(); } functionUpValues_.Remove(fucntion); Contract.Assert(fucntion.TempCount == 0); } public void PushBlock(LuaBlockSyntax block) { blocks_.Push(block); } public void PopBlock() { var block = blocks_.Pop(); if (block.TempCount > 0) { Contract.Assert(CurFunction.TempCount >= block.TempCount); CurFunction.TempCount -= block.TempCount; releaseTempIdentifierCount_ = 0; } } private LuaBlockSyntax CurBlock { get { return blocks_.Peek(); } } private LuaBlockSyntax CurBlockOrNull { get { return blocks_.Count > 0 ? blocks_.Peek() : null; } } private LuaIdentifierNameSyntax GetTempIdentifier() { int index = CurFunction.TempCount++; string name = LuaSyntaxNode.TempIdentifiers.GetOrDefault(index); if (name == null) { throw new CompilationErrorException($"Your code is startling,{LuaSyntaxNode.TempIdentifiers.Length} temporary variables is not enough"); } ++CurBlock.TempCount; return name; } private void ReleaseTempIdentifiers(int prevTempCount) { int count = CurFunction.TempCount - prevTempCount; PopTempCount(count); } private void PopTempCount(int count) { Contract.Assert(CurBlock.TempCount >= count && CurFunction.TempCount >= count); CurBlock.TempCount -= count; CurFunction.TempCount -= count; } private void AddReleaseTempIdentifier(LuaIdentifierNameSyntax tempName) { ++releaseTempIdentifierCount_; } private void ReleaseTempIdentifiers() { if (releaseTempIdentifierCount_ > 0) { PopTempCount(releaseTempIdentifierCount_); releaseTempIdentifierCount_ = 0; } } public LuaCompilationUnitSyntax VisitCompilationUnit(CompilationUnitSyntax node, bool isSingleFile = false) { LuaCompilationUnitSyntax compilationUnit = new LuaCompilationUnitSyntax(node.SyntaxTree.FilePath, !isSingleFile); compilationUnits_.Push(compilationUnit); var statements = VisitTriviaAndNode(node, node.Members, false); foreach (var statement in statements) { if (statement is LuaTypeDeclarationSyntax typeDeclaration) { var ns = new LuaNamespaceDeclarationSyntax(LuaIdentifierNameSyntax.Empty); ns.AddStatement(typeDeclaration); compilationUnit.AddStatement(ns); } else { compilationUnit.AddStatement(statement); } } var attributes = BuildAttributes(node.AttributeLists); generator_.WithAssemblyAttributes(attributes); compilationUnits_.Pop(); return compilationUnit; } public override LuaSyntaxNode VisitNamespaceDeclaration(NamespaceDeclarationSyntax node) { var symbol = semanticModel_.GetDeclaredSymbol(node); bool isContained = node.Parent.IsKind(SyntaxKind.NamespaceDeclaration); string name = generator_.GetNamespaceDefineName(symbol, node); LuaNamespaceDeclarationSyntax namespaceDeclaration = new LuaNamespaceDeclarationSyntax(name, isContained); var statements = VisitTriviaAndNode(node, node.Members); namespaceDeclaration.AddStatements(statements); return namespaceDeclaration; } private void BuildTypeMembers(LuaTypeDeclarationSyntax typeDeclaration, TypeDeclarationSyntax node) { foreach (var nestedTypeDeclaration in node.Members.Where(i => i.Kind().IsTypeDeclaration())) { var luaNestedTypeDeclaration = nestedTypeDeclaration.Accept<LuaTypeDeclarationSyntax>(this); typeDeclaration.AddNestedTypeDeclaration(luaNestedTypeDeclaration); } foreach (var member in node.Members.Where(i => !i.Kind().IsTypeDeclaration())) { member.Accept(this); } } private void CheckBaseTypeGenericKind(ref bool hasExtendSelf, INamedTypeSymbol typeSymbol, BaseTypeSyntax baseType) { if (!hasExtendSelf) { if (baseType.IsKind(SyntaxKind.SimpleBaseType)) { var baseNode = (SimpleBaseTypeSyntax)baseType; if (baseNode.Type.IsKind(SyntaxKind.GenericName)) { var baseGenericNameNode = (GenericNameSyntax)baseNode.Type; var baseTypeSymbol = (INamedTypeSymbol)semanticModel_.GetTypeInfo(baseGenericNameNode).Type; hasExtendSelf = Utility.IsExtendSelf(typeSymbol, baseTypeSymbol); } } } } private LuaSpeaicalGenericType CheckSpeaicalGenericArgument(INamedTypeSymbol typeSymbol) { var interfaceType = typeSymbol.AllInterfaces.FirstOrDefault(i => i.IsGenericIEnumerableType()); if (interfaceType != null) { bool isBaseImplementation = typeSymbol.BaseType != null && typeSymbol.BaseType.AllInterfaces.Any(i => i.IsGenericIEnumerableType()); if (!isBaseImplementation) { var argumentType = interfaceType.TypeArguments.First(); bool isLazy = argumentType.Kind != SymbolKind.TypeParameter && argumentType.IsFromCode(); var typeName = isLazy ? GetTypeNameWithoutImport(argumentType) : GetTypeName(argumentType); return new LuaSpeaicalGenericType() { Name = LuaIdentifierNameSyntax.GenericT, Value = typeName, IsLazy = isLazy }; } } return null; } private List<LuaIdentifierNameSyntax> GetBaseCopyFields(BaseTypeSyntax baseType) { if (baseType != null) { var fields = new List<LuaIdentifierNameSyntax>(); var semanticModel = generator_.GetSemanticModel(baseType.SyntaxTree); var baseTypeSymbol = semanticModel.GetTypeInfo(baseType.Type).Type; if (baseTypeSymbol.TypeKind == TypeKind.Class && baseTypeSymbol.SpecialType != SpecialType.System_Object) { if (baseTypeSymbol.IsMemberExists("Finalize", true)) { fields.Add(LuaIdentifierNameSyntax.__GC); } if (baseTypeSymbol.Is(generator_.SystemExceptionTypeSymbol)) { fields.Add(LuaIdentifierNameSyntax.__ToString); } } return fields; } return null; } private bool IsBaseTypeIgnore(ITypeSymbol symbol) { if (symbol.SpecialType == SpecialType.System_Object) { return true; } if (symbol.ContainingNamespace.IsRuntimeCompilerServices()) { return true; } return false; } private void BuildBaseTypes(INamedTypeSymbol typeSymbol, LuaTypeDeclarationSyntax typeDeclaration, IEnumerable<BaseTypeSyntax> types, bool isPartial) { bool hasExtendSelf = false; var baseTypes = new List<LuaExpressionSyntax>(); foreach (var baseType in types) { if (isPartial) { semanticModel_ = generator_.GetSemanticModel(baseType.SyntaxTree); } var baseTypeSymbol = semanticModel_.GetTypeInfo(baseType.Type).Type; if (!IsBaseTypeIgnore(baseTypeSymbol)) { var baseTypeName = BuildInheritTypeName(baseTypeSymbol); baseTypes.Add(baseTypeName); CheckBaseTypeGenericKind(ref hasExtendSelf, typeSymbol, baseType); } } if (baseTypes.Count > 0) { if (typeSymbol.IsRecordType()) { baseTypes.Add(GetRecordInerfaceTypeName(typeSymbol)); } var genericArgument = CheckSpeaicalGenericArgument(typeSymbol); var baseCopyFields = GetBaseCopyFields(types.FirstOrDefault()); typeDeclaration.AddBaseTypes(baseTypes, genericArgument, baseCopyFields); if (hasExtendSelf && !generator_.IsExplicitStaticCtorExists(typeSymbol)) { typeDeclaration.IsForceStaticCtor = true; } } } private void BuildTypeDeclaration(INamedTypeSymbol typeSymbol, TypeDeclarationSyntax node, LuaTypeDeclarationSyntax typeDeclaration) { typeDeclarations_.Push(new TypeDeclarationInfo(typeSymbol, typeDeclaration)); var comments = BuildDocumentationComment(node); typeDeclaration.AddDocument(comments); var attributes = BuildAttributes(node.AttributeLists); BuildTypeParameters(typeSymbol, node, typeDeclaration); if (node.BaseList != null) { BuildBaseTypes(typeSymbol, typeDeclaration, node.BaseList.Types, false); } CheckRecordParameterCtor(typeSymbol, node, typeDeclaration); BuildTypeMembers(typeDeclaration, node); CheckTypeDeclaration(typeSymbol, typeDeclaration, attributes, node); typeDeclarations_.Pop(); CurCompilationUnit.AddTypeDeclarationCount(); } private void CheckTypeDeclaration(INamedTypeSymbol typeSymbol, LuaTypeDeclarationSyntax typeDeclaration, List<LuaExpressionSyntax> attributes, BaseTypeDeclarationSyntax node) { if (typeDeclaration.IsNoneCtros) { var baseTypeSymbol = typeSymbol.BaseType; if (baseTypeSymbol != null) { bool isNeedCallBase; if (typeDeclaration.IsInitStatementExists) { isNeedCallBase = generator_.IsBaseExplicitCtorExists(baseTypeSymbol); } else { isNeedCallBase = generator_.HasStaticCtor(baseTypeSymbol); } if (isNeedCallBase) { var baseCtorInvoke = BuildCallBaseConstructor(typeSymbol); if (baseCtorInvoke != null) { var function = new LuaConstructorAdapterExpressionSyntax(); function.AddParameter(LuaIdentifierNameSyntax.This); function.AddStatement(baseCtorInvoke); typeDeclaration.AddCtor(function, false); } } } } else if (typeSymbol.IsValueType && !typeSymbol.IsCombineImplicitlyCtor()) { var function = new LuaConstructorAdapterExpressionSyntax(); function.AddParameter(LuaIdentifierNameSyntax.This); typeDeclaration.AddCtor(function, true); } if (typeSymbol.IsRecordType()) { if (typeSymbol.BaseType != null && typeSymbol.BaseType.SpecialType == SpecialType.System_Object) { typeDeclaration.AddBaseTypes(LuaIdentifierNameSyntax.RecordType.ArrayOf(GetRecordInerfaceTypeName(typeSymbol)), null, null); } BuildRecordMembers(typeSymbol, typeDeclaration); } if (typeDeclaration.IsIgnoreExport) { generator_.AddIgnoreExportType(typeSymbol); } if (IsCurTypeExportMetadataAll || attributes.Count > 0 || typeDeclaration.IsExportMetadata) { var data = new LuaTableExpression() { IsSingleLine = true }; data.Add(typeSymbol.GetMetaDataAttributeFlags()); data.AddRange(typeDeclaration.TypeParameterExpressions); data.AddRange(attributes); typeDeclaration.AddClassMetaData(data); } } private void CheckRecordParameterCtor(INamedTypeSymbol typeSymbol, TypeDeclarationSyntax node, LuaTypeDeclarationSyntax typeDeclaration) { if (typeSymbol.IsRecordType()) { var recordDeclaration = (RecordDeclarationSyntax)node; if (recordDeclaration.ParameterList != null) { BuildRecordParameterCtor(typeSymbol, typeDeclaration, recordDeclaration); } } } private void BuildRecordParameterCtor(INamedTypeSymbol typeSymbol, LuaTypeDeclarationSyntax typeDeclaration, RecordDeclarationSyntax recordDeclaration) { var parameterList = recordDeclaration.ParameterList.Accept<LuaParameterListSyntax>(this); var function = new LuaConstructorAdapterExpressionSyntax(); function.AddParameter(LuaIdentifierNameSyntax.This); function.AddParameters(parameterList.Parameters); function.AddStatements(parameterList.Parameters.Select(i => LuaIdentifierNameSyntax.This.MemberAccess(i).Assignment(i).ToStatementSyntax())); typeDeclaration.AddCtor(function, false); var ctor = typeSymbol.InstanceConstructors.First(); int index = 0; foreach (var p in ctor.Parameters) { var expression = GetFieldValueExpression(p.Type, null, out bool isLiteral, out _); if (expression != null) { typeDeclaration.AddField(parameterList.Parameters[index], expression, p.Type.IsImmutable() && isLiteral, false, false, true, null, false); } ++index; } } private void BuildRecordMembers(INamedTypeSymbol typeSymbol, LuaTypeDeclarationSyntax typeDeclaration) { var propertys = typeSymbol.GetMembers().OfType<IPropertySymbol>().Skip(1); var exprssions = new List<LuaExpressionSyntax>() { typeSymbol.Name.ToStringLiteral() }; exprssions.AddRange(propertys.Select(i => GetMemberName(i).ToStringLiteral())); var function = new LuaFunctionExpressionSyntax(); function.AddStatement(new LuaReturnStatementSyntax(exprssions)); typeDeclaration.AddMethod(LuaIdentifierNameSyntax.RecordMembers, function, false); } private INamedTypeSymbol VisitTypeDeclaration(INamedTypeSymbol typeSymbol, TypeDeclarationSyntax node, LuaTypeDeclarationSyntax typeDeclaration) { if (node.Modifiers.IsPartial()) { if (typeSymbol.DeclaringSyntaxReferences.Length > 1) { generator_.AddPartialTypeDeclaration(typeSymbol, node, typeDeclaration, CurCompilationUnit); typeDeclaration.IsPartialMark = true; } else { BuildTypeDeclaration(typeSymbol, node, typeDeclaration); } } else { BuildTypeDeclaration(typeSymbol, node, typeDeclaration); } return typeSymbol; } internal void AcceptPartialType(PartialTypeDeclaration major, IEnumerable<PartialTypeDeclaration> typeDeclarations) { compilationUnits_.Push(major.CompilationUnit); typeDeclarations_.Push(new TypeDeclarationInfo(major.Symbol, major.TypeDeclaration)); List<LuaExpressionSyntax> attributes = new List<LuaExpressionSyntax>(); foreach (var typeDeclaration in typeDeclarations) { semanticModel_ = generator_.GetSemanticModel(typeDeclaration.Node.SyntaxTree); var document = BuildDocumentationComment(typeDeclaration.Node); major.TypeDeclaration.AddDocument(document); var expressions = BuildAttributes(typeDeclaration.Node.AttributeLists); attributes.AddRange(expressions); } BuildTypeParameters(major.Symbol, major.Node, major.TypeDeclaration); List<BaseTypeSyntax> baseTypes = new List<BaseTypeSyntax>(); HashSet<ITypeSymbol> baseSymbols = new HashSet<ITypeSymbol>(); foreach (var typeDeclaration in typeDeclarations) { if (typeDeclaration.Node.BaseList != null) { foreach (var baseTypeSyntax in typeDeclaration.Node.BaseList.Types) { var semanticModel = generator_.GetSemanticModel(baseTypeSyntax.SyntaxTree); var baseTypeSymbol = semanticModel.GetTypeInfo(baseTypeSyntax.Type).Type; if (baseSymbols.Add(baseTypeSymbol)) { baseTypes.Add(baseTypeSyntax); } } } } if (baseTypes.Count > 0) { if (baseTypes.Count > 1) { var baseTypeIndex = baseTypes.FindIndex(generator_.IsBaseType); if (baseTypeIndex > 0) { var baseType = baseTypes[baseTypeIndex]; baseTypes.RemoveAt(baseTypeIndex); baseTypes.Insert(0, baseType); } } BuildBaseTypes(major.Symbol, major.TypeDeclaration, baseTypes, true); } foreach (var typeDeclaration in typeDeclarations) { semanticModel_ = generator_.GetSemanticModel(typeDeclaration.Node.SyntaxTree); BuildTypeMembers(major.TypeDeclaration, typeDeclaration.Node); } CheckTypeDeclaration(major.Symbol, major.TypeDeclaration, attributes, major.Node); typeDeclarations_.Pop(); compilationUnits_.Pop(); major.TypeDeclaration.IsPartialMark = false; major.CompilationUnit.AddTypeDeclarationCount(); } private void GetTypeDeclarationName(BaseTypeDeclarationSyntax typeDeclaration, out LuaIdentifierNameSyntax name, out INamedTypeSymbol typeSymbol) { typeSymbol = semanticModel_.GetDeclaredSymbol(typeDeclaration); name = generator_.GetTypeDeclarationName(typeSymbol); } public override LuaSyntaxNode VisitClassDeclaration(ClassDeclarationSyntax node) { GetTypeDeclarationName(node, out var name, out var typeSymbol); LuaClassDeclarationSyntax classDeclaration = new LuaClassDeclarationSyntax(name); VisitTypeDeclaration(typeSymbol, node, classDeclaration); return classDeclaration; } public override LuaSyntaxNode VisitStructDeclaration(StructDeclarationSyntax node) { GetTypeDeclarationName(node, out var name, out var typeSymbol); LuaStructDeclarationSyntax structDeclaration = new LuaStructDeclarationSyntax(name); VisitTypeDeclaration(typeSymbol, node, structDeclaration); return structDeclaration; } public override LuaSyntaxNode VisitInterfaceDeclaration(InterfaceDeclarationSyntax node) { GetTypeDeclarationName(node, out var name, out var typeSymbol); var interfaceDeclaration = new LuaInterfaceDeclarationSyntax(name); VisitTypeDeclaration(typeSymbol, node, interfaceDeclaration); return interfaceDeclaration; } private void VisitEnumDeclaration(INamedTypeSymbol typeSymbol, EnumDeclarationSyntax node, LuaEnumDeclarationSyntax enumDeclaration) { typeDeclarations_.Push(new TypeDeclarationInfo(typeSymbol, enumDeclaration)); var document = BuildDocumentationComment(node); enumDeclaration.AddDocument(document); var attributes = BuildAttributes(node.AttributeLists); foreach (var member in node.Members) { var statement = member.Accept<LuaKeyValueTableItemSyntax>(this); enumDeclaration.Add(statement); } CheckTypeDeclaration(typeSymbol, enumDeclaration, attributes, node); typeDeclarations_.Pop(); generator_.AddEnumDeclaration(typeSymbol, enumDeclaration); } public override LuaSyntaxNode VisitEnumDeclaration(EnumDeclarationSyntax node) { GetTypeDeclarationName(node, out var name, out var typeSymbol); LuaEnumDeclarationSyntax enumDeclaration = new LuaEnumDeclarationSyntax(typeSymbol.ToString(), name, CurCompilationUnit); VisitEnumDeclaration(typeSymbol, node, enumDeclaration); return enumDeclaration; } public override LuaSyntaxNode VisitRecordDeclaration(RecordDeclarationSyntax node) { GetTypeDeclarationName(node, out var name, out var typeSymbol); LuaClassDeclarationSyntax classDeclaration = new LuaClassDeclarationSyntax(name); VisitTypeDeclaration(typeSymbol, node, classDeclaration); return classDeclaration; } public override LuaSyntaxNode VisitDelegateDeclaration(DelegateDeclarationSyntax node) { return LuaStatementSyntax.Empty; } private void VisitYield(IMethodSymbol symbol, LuaFunctionExpressionSyntax function) { var retrurnTypeSymbol = (INamedTypeSymbol)symbol.ReturnType; string name = LuaSyntaxNode.Tokens.Yield + retrurnTypeSymbol.Name; var invokeExpression = LuaIdentifierNameSyntax.System.MemberAccess(name).Invocation(); var wrapFunction = new LuaFunctionExpressionSyntax(); if (symbol.IsAsync) { wrapFunction.AddParameter(LuaIdentifierNameSyntax.Async); } var parameters = function.ParameterList.Parameters; wrapFunction.ParameterList.Parameters.AddRange(parameters); wrapFunction.AddStatements(function.Body.Statements); invokeExpression.AddArgument(wrapFunction); if (retrurnTypeSymbol.IsGenericType) { var typeName = retrurnTypeSymbol.TypeArguments.First(); var expression = GetTypeName(typeName); invokeExpression.AddArgument(expression); } else { invokeExpression.AddArgument(LuaIdentifierNameSyntax.Object); } invokeExpression.ArgumentList.Arguments.AddRange(parameters); var returnStatement = new LuaReturnStatementSyntax(invokeExpression); function.Body.Statements.Clear(); function.AddStatement(returnStatement); } private void VisitAsync(bool returnsVoid, LuaFunctionExpressionSyntax function) { var invokeExpression = LuaIdentifierNameSyntax.System.MemberAccess(LuaIdentifierNameSyntax.Async).Invocation(); var wrapFunction = new LuaFunctionExpressionSyntax(); var parameters = function.ParameterList.Parameters; wrapFunction.AddParameter(LuaIdentifierNameSyntax.Async); wrapFunction.ParameterList.Parameters.AddRange(parameters); wrapFunction.AddStatements(function.Body.Statements); invokeExpression.AddArgument(wrapFunction); invokeExpression.AddArgument(returnsVoid ? LuaIdentifierNameSyntax.True : LuaIdentifierNameSyntax.Nil); invokeExpression.ArgumentList.Arguments.AddRange(parameters); function.Body.Statements.Clear(); if (returnsVoid) { function.AddStatement(invokeExpression); } else { function.AddStatement(new LuaReturnStatementSyntax(invokeExpression)); } } private sealed class MethodDeclarationResult { public IMethodSymbol Symbol; public LuaFunctionExpressionSyntax Function; public bool IsPrivate; public LuaIdentifierNameSyntax Name; public LuaDocumentStatement Document; public List<LuaExpressionSyntax> Attributes; public bool IsIgnore => Document != null && Document.HasIgnoreAttribute; public bool IsMetadata => (Document != null && Document.HasMetadataAttribute); } private void AddMethodMetaData(MethodDeclarationResult result, bool isMoreThanLocalVariables = false) { var table = new LuaTableExpression() { IsSingleLine = true }; table.Add(new LuaStringLiteralExpressionSyntax(result.Symbol.Name)); table.Add(result.Symbol.GetMetaDataAttributeFlags()); if (isMoreThanLocalVariables) { table.Add(LuaIdentifierNameSyntax.MorenManyLocalVarTempTable.MemberAccess(result.Name)); } else { table.Add(result.Name); } var parameters = result.Symbol.Parameters.Select(i => GetTypeNameOfMetadata(i.Type)).ToList(); if (!result.Symbol.ReturnsVoid) { parameters.Add(GetTypeNameOfMetadata(result.Symbol.ReturnType)); } if (result.Symbol.IsGenericMethod) { var function = new LuaFunctionExpressionSyntax(); function.AddParameters(result.Symbol.TypeParameters.Select(i => (LuaIdentifierNameSyntax)i.Name)); function.AddStatement(new LuaReturnStatementSyntax(parameters)); table.Add(function); } else { table.AddRange(parameters); } table.AddRange(result.Attributes); CurType.AddMethodMetaData(table); } private MethodDeclarationResult BuildMethodDeclaration( CSharpSyntaxNode node, SyntaxList<AttributeListSyntax> attributeLists, ParameterListSyntax parameterList, TypeParameterListSyntax typeParameterList, BlockSyntax body, ArrowExpressionClauseSyntax expressionBody) { IMethodSymbol symbol = (IMethodSymbol)semanticModel_.GetDeclaredSymbol(node); var refOrOutParameters = new List<LuaExpressionSyntax>(); MethodInfo methodInfo = new MethodInfo(symbol, refOrOutParameters); methodInfos_.Push(methodInfo); LuaIdentifierNameSyntax methodName; if (symbol.MethodKind == MethodKind.LocalFunction) { methodName = GetLocalMethodName(symbol, node); } else { methodName = GetMemberName(symbol); } LuaFunctionExpressionSyntax function = new LuaFunctionExpressionSyntax(); PushFunction(function); var document = BuildDocumentationComment(node); bool isPrivate = symbol.IsPrivate() && symbol.ExplicitInterfaceImplementations.IsEmpty; if (!symbol.IsStatic && symbol.MethodKind != MethodKind.LocalFunction) { function.AddParameter(LuaIdentifierNameSyntax.This); if (isPrivate) { if (generator_.IsForcePublicSymbol(symbol) || generator_.IsMonoBehaviourSpecialMethod(symbol)) { isPrivate = false; } } } else if (symbol.IsMainEntryPoint()) { isPrivate = false; generator_.SetMainEntryPoint(symbol, node); } else if (isPrivate && generator_.IsForcePublicSymbol(symbol)) { isPrivate = false; } var attributes = BuildAttributes(attributeLists); foreach (var parameterNode in parameterList.Parameters) { var parameter = parameterNode.Accept<LuaIdentifierNameSyntax>(this); function.AddParameter(parameter); if (parameterNode.Modifiers.IsOutOrRef()) { refOrOutParameters.Add(parameter); } else if (parameterNode.Modifiers.IsParams() && symbol.HasParamsAttribute()) { function.ParameterList.Parameters[^1] = LuaSyntaxNode.Tokens.Params; } } if (typeParameterList != null) { var typeParameters = typeParameterList.Accept<LuaParameterListSyntax>(this); function.AddParameters(typeParameters.Parameters); } if (body != null) { var block = body.Accept<LuaBlockSyntax>(this); function.AddStatements(block.Statements); } else { var expression = expressionBody.AcceptExpression(this); if (symbol.ReturnsVoid) { function.AddStatement(expression); } else { var returnStatement = new LuaReturnStatementSyntax(expression); returnStatement.Expressions.AddRange(refOrOutParameters); function.AddStatement(returnStatement); } } if (methodInfo.HasYield) { VisitYield(symbol, function); } else if (symbol.IsAsync) { VisitAsync(symbol.ReturnsVoid, function); } else { if (symbol.ReturnsVoid && refOrOutParameters.Count > 0) { function.AddStatement(new LuaReturnStatementSyntax(refOrOutParameters)); } } PopFunction(); methodInfos_.Pop(); return new MethodDeclarationResult { Symbol = symbol, Name = methodName, Function = function, IsPrivate = isPrivate, Document = document, Attributes = attributes, }; } private bool IsCurTypeExportMetadataAll { get { return generator_.Setting.IsExportMetadata || CurType.IsExportMetadataAll; } } private bool IsCurTypeSerializable { get { return IsCurTypeExportMetadataAll || CurTypeSymbol.IsSerializable; } } private static bool IsExportMethodDeclaration(BaseMethodDeclarationSyntax node) { return (node.Body != null || node.ExpressionBody != null) && !node.HasCSharpLuaAttribute(LuaDocumentStatement.AttributeFlags.Ignore); } public override LuaSyntaxNode VisitMethodDeclaration(MethodDeclarationSyntax node) { if (IsExportMethodDeclaration(node)) { var result = BuildMethodDeclaration(node, node.AttributeLists, node.ParameterList, node.TypeParameterList, node.Body, node.ExpressionBody); bool isMoreThanLocalVariables = IsMoreThanLocalVariables(result.Symbol); CurType.AddMethod(result.Name, result.Function, result.IsPrivate, result.Document, isMoreThanLocalVariables, result.Symbol.IsInterfaceDefaultMethod()); if (IsCurTypeExportMetadataAll || result.Attributes.Count > 0 || result.IsMetadata) { AddMethodMetaData(result, isMoreThanLocalVariables); } return result.Function; } return base.VisitMethodDeclaration(node); } private LuaExpressionSyntax BuildEnumNoConstantDefaultValue(ITypeSymbol typeSymbol) { var typeName = GetTypeName(typeSymbol); var field = typeSymbol.GetMembers().OfType<IFieldSymbol>().FirstOrDefault(i => i.ConstantValue.Equals(0)); if (field != null) { return typeName.MemberAccess(field.Name); } return typeName.Invocation(LuaNumberLiteralExpressionSyntax.Zero); } private LuaExpressionSyntax GetPredefinedValueTypeDefaultValue(ITypeSymbol typeSymbol) { switch (typeSymbol.SpecialType) { case SpecialType.None: { if (typeSymbol.TypeKind == TypeKind.Enum) { if (!generator_.IsConstantEnum(typeSymbol)) { return BuildEnumNoConstantDefaultValue(typeSymbol); } return LuaNumberLiteralExpressionSyntax.Zero; } else if (typeSymbol.IsTimeSpanType()) { return BuildDefaultValue(LuaIdentifierNameSyntax.TimeSpan); } return null; } case SpecialType.System_Boolean: { return new LuaIdentifierLiteralExpressionSyntax(LuaIdentifierNameSyntax.False); } case SpecialType.System_Char: { return new LuaCharacterLiteralExpression(default); } case SpecialType.System_SByte: case SpecialType.System_Byte: case SpecialType.System_Int16: case SpecialType.System_UInt16: case SpecialType.System_Int32: case SpecialType.System_UInt32: case SpecialType.System_Int64: case SpecialType.System_UInt64: { return LuaNumberLiteralExpressionSyntax.Zero; } case SpecialType.System_Single: case SpecialType.System_Double: { return LuaNumberLiteralExpressionSyntax.ZeroFloat; } case SpecialType.System_DateTime: { return BuildDefaultValue(LuaIdentifierNameSyntax.DateTime); } default: return null; } } private static LuaInvocationExpressionSyntax BuildDefaultValue(LuaExpressionSyntax typeExpression) { return new LuaInvocationExpressionSyntax(LuaIdentifierNameSyntax.SystemDefault, typeExpression); } private void AddFieldMetaData(IFieldSymbol symbol, LuaIdentifierNameSyntax fieldName, List<LuaExpressionSyntax> attributes) { var data = new LuaTableExpression() { IsSingleLine = true }; data.Add(new LuaStringLiteralExpressionSyntax(symbol.Name)); data.Add(symbol.GetMetaDataAttributeFlags()); data.Add(GetTypeNameOfMetadata(symbol.Type)); if (generator_.IsNeedRefactorName(symbol)) { data.Add(new LuaStringLiteralExpressionSyntax(fieldName)); } data.AddRange(attributes); CurType.AddFieldMetaData(data); } private void VisitBaseFieldDeclarationSyntax(BaseFieldDeclarationSyntax node) { if (!node.Modifiers.IsConst()) { bool isStatic = node.Modifiers.IsStatic(); bool isPrivate = node.Modifiers.IsPrivate(); bool isReadOnly = node.Modifiers.IsReadOnly(); var attributes = BuildAttributes(node.AttributeLists); var type = node.Declaration.Type; ITypeSymbol typeSymbol = (ITypeSymbol)semanticModel_.GetSymbolInfo(type).Symbol; bool isImmutable = typeSymbol.IsImmutable(); foreach (var variable in node.Declaration.Variables) { var variableSymbol = semanticModel_.GetDeclaredSymbol(variable); if (variableSymbol.IsAbstract) { continue; } if (node.IsKind(SyntaxKind.EventFieldDeclaration)) { var eventSymbol = (IEventSymbol)variableSymbol; if (!IsEventFiled(eventSymbol)) { var eventName = GetMemberName(eventSymbol); var innerName = AddInnerName(eventSymbol); LuaExpressionSyntax valueExpression = GetFieldValueExpression(typeSymbol, variable.Initializer?.Value, out bool valueIsLiteral, out var statements); LuaExpressionSyntax typeExpression = null; if (isStatic) { typeExpression = GetTypeName(eventSymbol.ContainingType); } var (add, remove) = CurType.AddEvent(eventName, innerName, valueExpression, isImmutable && valueIsLiteral, isStatic, isPrivate, typeExpression, statements); if (attributes.Count > 0 || variableSymbol.HasMetadataAttribute()) { AddPropertyOrEventMetaData(variableSymbol, new PropertyMethodResult(add), new PropertyMethodResult(remove), null, attributes); } continue; } } else { if (!isStatic && isPrivate) { var fieldSymbol = (IFieldSymbol)variableSymbol; if (fieldSymbol.IsProtobufNetSpecialField(out string name)) { AddField(name, typeSymbol, variable.Initializer?.Value, isImmutable, isStatic, isPrivate, isReadOnly, attributes); continue; } } } if (isPrivate && generator_.IsForcePublicSymbol(variableSymbol)) { isPrivate = false; } var fieldName = GetMemberName(variableSymbol); AddField(fieldName, typeSymbol, variable.Initializer?.Value, isImmutable, isStatic, isPrivate, isReadOnly, attributes); if (IsCurTypeSerializable || attributes.Count > 0 || variableSymbol.HasMetadataAttribute()) { if (variableSymbol.Kind == SymbolKind.Field) { AddFieldMetaData((IFieldSymbol)variableSymbol, fieldName, attributes); } else { AddPropertyOrEventMetaData(variableSymbol, null, null, fieldName, attributes); } } } } else { bool isPrivate = node.Modifiers.IsPrivate(); var type = node.Declaration.Type; ITypeSymbol typeSymbol = (ITypeSymbol)semanticModel_.GetSymbolInfo(type).Symbol; if (typeSymbol.SpecialType == SpecialType.System_String) { foreach (var variable in node.Declaration.Variables) { var constValue = semanticModel_.GetConstantValue(variable.Initializer.Value); Contract.Assert(constValue.HasValue); string v = (string)constValue.Value; if (v != null) { if (v.Length > kStringConstInlineCount) { var variableSymbol = semanticModel_.GetDeclaredSymbol(variable); if (isPrivate && generator_.IsForcePublicSymbol(variableSymbol)) { isPrivate = false; } var attributes = BuildAttributes(node.AttributeLists); var fieldName = GetMemberName(variableSymbol); bool isMoreThanLocalVariables = IsMoreThanLocalVariables(variableSymbol); AddField(fieldName, typeSymbol, variable.Initializer.Value, true, true, isPrivate, true, attributes, isMoreThanLocalVariables); } } } } } } public override LuaSyntaxNode VisitFieldDeclaration(FieldDeclarationSyntax node) { VisitBaseFieldDeclarationSyntax(node); return base.VisitFieldDeclaration(node); } private LuaExpressionSyntax GetFieldValueExpression(ITypeSymbol typeSymbol, ExpressionSyntax expression, out bool valueIsLiteral, out List<LuaStatementSyntax> statements) { LuaExpressionSyntax valueExpression = null; valueIsLiteral = false; statements = null; if (expression != null && !expression.IsKind(SyntaxKind.NullLiteralExpression)) { var function = new LuaFunctionExpressionSyntax(); PushFunction(function); valueExpression = VisitExpression(expression); PopFunction(); if (function.Body.Statements.Count > 0) { statements = function.Body.Statements; } LuaExpressionSyntax v = valueExpression; if (valueExpression is LuaPrefixUnaryExpressionSyntax prefixUnaryExpression) { v = prefixUnaryExpression.Operand; } valueIsLiteral = v is LuaLiteralExpressionSyntax; } if (valueExpression == null) { if (typeSymbol.IsMaybeValueType() && !typeSymbol.IsNullableType()) { var defalutValue = GetPredefinedValueTypeDefaultValue(typeSymbol); if (defalutValue != null) { valueExpression = defalutValue; valueIsLiteral = defalutValue is LuaLiteralExpressionSyntax; } else { valueExpression = GetDefaultValueExpression(typeSymbol); } } } return valueExpression; } private void AddField(LuaIdentifierNameSyntax name, ITypeSymbol typeSymbol, ExpressionSyntax expression, bool isImmutable, bool isStatic, bool isPrivate, bool isReadOnly, List<LuaExpressionSyntax> attributes, bool isMoreThanLocalVariables = false) { var valueExpression = GetFieldValueExpression(typeSymbol, expression, out bool valueIsLiteral, out var statements); CurType.AddField(name, valueExpression, isImmutable && valueIsLiteral, isStatic, isPrivate, isReadOnly, statements, isMoreThanLocalVariables); } private sealed class PropertyMethodResult { public LuaPropertyOrEventIdentifierNameSyntax Name { get; } public List<LuaExpressionSyntax> Attributes { get; } public PropertyMethodResult(LuaPropertyOrEventIdentifierNameSyntax name, List<LuaExpressionSyntax> attributes = null) { Name = name; Attributes = attributes; } } private void AddPropertyOrEventMetaData(ISymbol symol, PropertyMethodResult get, PropertyMethodResult set, LuaIdentifierNameSyntax name, List<LuaExpressionSyntax> attributes) { bool isProperty = symol.Kind == SymbolKind.Property; PropertyMethodKind kind; if (get != null) { if (set != null) { kind = PropertyMethodKind.Both; } else { kind = PropertyMethodKind.GetOnly; } } else { if (set != null) { kind = PropertyMethodKind.SetOnly; } else { kind = PropertyMethodKind.Field; } } var data = new LuaTableExpression() { IsSingleLine = true }; data.Add(new LuaStringLiteralExpressionSyntax(symol.Name)); data.Add(symol.GetMetaDataAttributeFlags(kind)); var type = isProperty ? ((IPropertySymbol)symol).Type : ((IEventSymbol)symol).Type; data.Add(GetTypeNameOfMetadata(type)); if (kind == PropertyMethodKind.Field) { if (generator_.IsNeedRefactorName(symol)) { data.Add(new LuaStringLiteralExpressionSyntax(name)); } } else { if (get != null) { if (get.Attributes.IsNullOrEmpty()) { data.Add(get.Name); } else { var getTable = new LuaTableExpression(); getTable.Add(get.Name); getTable.AddRange(get.Attributes); data.Add(getTable); } } if (set != null) { if (set.Attributes.IsNullOrEmpty()) { data.Add(set.Name); } else { var setTable = new LuaTableExpression(); setTable.Add(set.Name); setTable.AddRange(set.Attributes); data.Add(setTable); } } } data.AddRange(attributes); if (isProperty) { CurType.AddPropertyMetaData(data); } else { CurType.AddEventMetaData(data); } } public override LuaSyntaxNode VisitPropertyDeclaration(PropertyDeclarationSyntax node) { var symbol = semanticModel_.GetDeclaredSymbol(node); if (!symbol.IsAbstract) { if (symbol.IsProtobufNetSpecialProperty()) { return null; } bool isStatic = symbol.IsStatic; bool isPrivate = symbol.IsPrivate() && symbol.ExplicitInterfaceImplementations.IsEmpty; bool hasGet = false; bool hasSet = false; if (isPrivate && generator_.IsForcePublicSymbol(symbol)) { isPrivate = false; } var propertyName = GetMemberName(symbol); var attributes = BuildAttributes(node.AttributeLists); PropertyMethodResult getMethod = null; PropertyMethodResult setMethod = null; if (node.AccessorList != null) { foreach (var accessor in node.AccessorList.Accessors) { if (accessor.Body != null || accessor.ExpressionBody != null) { var accessorSymbol = semanticModel_.GetDeclaredSymbol(accessor); var methodInfo = new MethodInfo(accessorSymbol); methodInfos_.Push(methodInfo); bool isGet = accessor.IsKind(SyntaxKind.GetAccessorDeclaration); var functionExpression = new LuaFunctionExpressionSyntax(); if (!isStatic) { functionExpression.AddParameter(LuaIdentifierNameSyntax.This); } PushFunction(functionExpression); if (accessor.Body != null) { var block = accessor.Body.Accept<LuaBlockSyntax>(this); functionExpression.AddStatements(block.Statements); } else { var bodyExpression = accessor.ExpressionBody.AcceptExpression(this); if (isGet) { functionExpression.AddStatement(new LuaReturnStatementSyntax(bodyExpression)); } else { functionExpression.AddStatement(bodyExpression); } } if (methodInfo.HasYield) { VisitYield(accessorSymbol, functionExpression); } PopFunction(); methodInfos_.Pop(); var name = new LuaPropertyOrEventIdentifierNameSyntax(true, propertyName); CurType.AddMethod(name, functionExpression, isPrivate, null, IsMoreThanLocalVariables(accessorSymbol)); var methodAttributes = BuildAttributes(accessor.AttributeLists); if (isGet) { Contract.Assert(!hasGet); hasGet = true; getMethod = new PropertyMethodResult(name, methodAttributes); } else { Contract.Assert(!hasSet); functionExpression.AddParameter(LuaIdentifierNameSyntax.Value); name.IsGetOrAdd = false; hasSet = true; setMethod = new PropertyMethodResult(name, methodAttributes); } } } } else { Contract.Assert(!hasGet); methodInfos_.Push(new MethodInfo(symbol.GetMethod)); var name = new LuaPropertyOrEventIdentifierNameSyntax(true, propertyName); var functionExpression = new LuaFunctionExpressionSyntax(); PushFunction(functionExpression); var expression = node.ExpressionBody.AcceptExpression(this); PopFunction(); methodInfos_.Pop(); if (!isStatic) { functionExpression.AddParameter(LuaIdentifierNameSyntax.This); } var returnStatement = new LuaReturnStatementSyntax(expression); functionExpression.AddStatement(returnStatement); CurType.AddMethod(name, functionExpression, isPrivate); hasGet = true; getMethod = new PropertyMethodResult(name); } if (!hasGet && !hasSet) { ITypeSymbol typeSymbol = symbol.Type; bool isImmutable = typeSymbol.IsImmutable(); bool isField = IsPropertyField(semanticModel_.GetDeclaredSymbol(node)); if (isField) { bool isReadOnly = IsReadOnlyProperty(node); AddField(propertyName, typeSymbol, node.Initializer?.Value, isImmutable, isStatic, isPrivate, isReadOnly, attributes); } else { var innerName = AddInnerName(symbol); var valueExpression = GetFieldValueExpression(typeSymbol, node.Initializer?.Value, out bool valueIsLiteral, out var statements); LuaExpressionSyntax typeExpression = null; if (isStatic) { typeExpression = GetTypeName(symbol.ContainingType); } bool isGetOnly = symbol.SetMethod == null; var (getName, setName) = CurType.AddProperty(propertyName, innerName, valueExpression, isImmutable && valueIsLiteral, isStatic, isPrivate, typeExpression, statements, isGetOnly); getMethod = new PropertyMethodResult(getName); setMethod = isGetOnly ? null : new PropertyMethodResult(setName); } } if (IsCurTypeSerializable || attributes.Count > 0 || symbol.HasMetadataAttribute()) { AddPropertyOrEventMetaData(symbol, getMethod, setMethod, propertyName, attributes); } } return base.VisitPropertyDeclaration(node); } private bool IsReadOnlyProperty(PropertyDeclarationSyntax node) { return node.AccessorList.Accessors.Count == 1 && node.AccessorList.Accessors[0].Body == null; } public override LuaSyntaxNode VisitEventDeclaration(EventDeclarationSyntax node) { var symbol = semanticModel_.GetDeclaredSymbol(node); if (!symbol.IsAbstract) { var attributes = BuildAttributes(node.AttributeLists); bool isStatic = symbol.IsStatic; bool isPrivate = symbol.IsPrivate() && symbol.ExplicitInterfaceImplementations.IsEmpty; var eventName = GetMemberName(symbol); PropertyMethodResult addMethod = null; PropertyMethodResult removeMethod = null; foreach (var accessor in node.AccessorList.Accessors) { var methodAttributes = BuildAttributes(accessor.AttributeLists); var functionExpression = new LuaFunctionExpressionSyntax(); if (!isStatic) { functionExpression.AddParameter(LuaIdentifierNameSyntax.This); } functionExpression.AddParameter(LuaIdentifierNameSyntax.Value); PushFunction(functionExpression); if (accessor.Body != null) { var block = accessor.Body.Accept<LuaBlockSyntax>(this); functionExpression.AddStatements(block.Statements); } else { var bodyExpression = accessor.ExpressionBody.AcceptExpression(this); functionExpression.AddStatement(bodyExpression); } PopFunction(); var name = new LuaPropertyOrEventIdentifierNameSyntax(false, eventName); CurType.AddMethod(name, functionExpression, isPrivate); if (accessor.IsKind(SyntaxKind.RemoveAccessorDeclaration)) { name.IsGetOrAdd = false; removeMethod = new PropertyMethodResult(name, methodAttributes); } else { addMethod = new PropertyMethodResult(name, methodAttributes); } } if (attributes.Count > 0 || symbol.HasMetadataAttribute()) { AddPropertyOrEventMetaData(symbol, addMethod, removeMethod, null, attributes); } } return base.VisitEventDeclaration(node); } public override LuaSyntaxNode VisitEventFieldDeclaration(EventFieldDeclarationSyntax node) { VisitBaseFieldDeclarationSyntax(node); return base.VisitEventFieldDeclaration(node); } public override LuaSyntaxNode VisitEnumMemberDeclaration(EnumMemberDeclarationSyntax node) { IFieldSymbol symbol = semanticModel_.GetDeclaredSymbol(node); Contract.Assert(symbol.HasConstantValue); var attributes = BuildAttributes(node.AttributeLists); LuaIdentifierNameSyntax identifier = node.Identifier.ValueText; AddFieldMetaData(symbol, identifier, attributes); var value = new LuaIdentifierLiteralExpressionSyntax(symbol.ConstantValue.ToString()); return new LuaKeyValueTableItemSyntax(identifier, value); } public override LuaSyntaxNode VisitIndexerDeclaration(IndexerDeclarationSyntax node) { var symbol = semanticModel_.GetDeclaredSymbol(node); if (!symbol.IsAbstract) { bool isPrivate = symbol.IsPrivate(); var indexName = GetMemberName(symbol); var parameterList = node.ParameterList.Accept<LuaParameterListSyntax>(this); void Fill(Action<LuaFunctionExpressionSyntax, LuaPropertyOrEventIdentifierNameSyntax> action) { var function = new LuaFunctionExpressionSyntax(); function.AddParameter(LuaIdentifierNameSyntax.This); function.ParameterList.Parameters.AddRange(parameterList.Parameters); var name = new LuaPropertyOrEventIdentifierNameSyntax(true, indexName); PushFunction(function); action(function, name); PopFunction(); CurType.AddMethod(name, function, isPrivate); } if (node.AccessorList != null) { foreach (var accessor in node.AccessorList.Accessors) { Fill((function, name) => { bool isGet = accessor.IsKind(SyntaxKind.GetAccessorDeclaration); if (accessor.Body != null) { var block = accessor.Body.Accept<LuaBlockSyntax>(this); function.AddStatements(block.Statements); } else { var bodyExpression = accessor.ExpressionBody.AcceptExpression(this); if (isGet) { function.AddStatement(new LuaReturnStatementSyntax(bodyExpression)); } else { function.AddStatement(bodyExpression); } } if (!isGet) { function.AddParameter(LuaIdentifierNameSyntax.Value); name.IsGetOrAdd = false; } }); } } else { Fill((function, name) => { var bodyExpression = node.ExpressionBody.AcceptExpression(this); function.AddStatement(new LuaReturnStatementSyntax(bodyExpression)); }); } } return base.VisitIndexerDeclaration(node); } public override LuaSyntaxNode VisitBracketedParameterList(BracketedParameterListSyntax node) { return BuildParameterList(node.Parameters); } public override LuaSyntaxNode VisitParameterList(ParameterListSyntax node) { return BuildParameterList(node.Parameters); } private LuaSyntaxNode BuildParameterList(SeparatedSyntaxList<ParameterSyntax> parameters) { var parameterList = new LuaParameterListSyntax(); foreach (var parameter in parameters) { var newNode = parameter.Accept<LuaIdentifierNameSyntax>(this); parameterList.Parameters.Add(newNode); } return parameterList; } public override LuaSyntaxNode VisitParameter(ParameterSyntax node) { LuaIdentifierNameSyntax identifier = node.Identifier.ValueText; CheckLocalVariableName(ref identifier, node); return identifier; } private sealed class BlockCommonNode : IComparable<BlockCommonNode> { public SyntaxTrivia SyntaxTrivia { get; } public CSharpSyntaxNode SyntaxNode { get; } public FileLinePositionSpan LineSpan { get; } public BlockCommonNode(SyntaxTrivia syntaxTrivia) { SyntaxTrivia = syntaxTrivia; LineSpan = syntaxTrivia.SyntaxTree.GetLineSpan(syntaxTrivia.Span); } public BlockCommonNode(CSharpSyntaxNode statement) { SyntaxNode = statement; LineSpan = statement.SyntaxTree.GetLineSpan(statement.Span); } public int CompareTo(BlockCommonNode other) { return LineSpan.StartLinePosition.CompareTo(other.LineSpan.StartLinePosition); } public bool Contains(BlockCommonNode other) { var otherLineSpan = other.LineSpan; return otherLineSpan.StartLinePosition > LineSpan.StartLinePosition && otherLineSpan.EndLinePosition < LineSpan.EndLinePosition; } public LuaBlankLinesStatement CheckBlankLine(ref int lastLine) { LuaBlankLinesStatement statement = null; if (lastLine != -1) { if (SyntaxTrivia != null && SyntaxTrivia.Kind() == SyntaxKind.DisabledTextTrivia) { ++lastLine; } int count = LineSpan.StartLinePosition.Line - lastLine - 1; if (count > 0) { statement = new LuaBlankLinesStatement(count); } } lastLine = LineSpan.EndLinePosition.Line; return statement; } public LuaSyntaxNode Visit(LuaSyntaxNodeTransform transfor) { const int kCommentCharCount = 2; if (SyntaxNode != null) { try { var node = SyntaxNode.Accept(transfor); if (node == null) { throw new InvalidOperationException(); } return node; } catch (CompilationErrorException e) { throw e.With(SyntaxNode); } catch (BugErrorException) { throw; } catch (Exception e) { if (e.InnerException is CompilationErrorException ex) { throw ex.With(SyntaxNode); } throw new BugErrorException(SyntaxNode, e); } } else { string content = SyntaxTrivia.ToString(); switch (SyntaxTrivia.Kind()) { case SyntaxKind.SingleLineCommentTrivia: { string commentContent = content.Substring(kCommentCharCount); return new LuaShortCommentStatement(commentContent); } case SyntaxKind.MultiLineCommentTrivia: { string commentContent = content[kCommentCharCount..^kCommentCharCount]; commentContent = commentContent.ReplaceNewline(); if (CheckInsertLuaCodeTemplate(commentContent, out var codeStatement)) { return codeStatement; } return new LuaLongCommentStatement(commentContent); } case SyntaxKind.SingleLineDocumentationCommentTrivia: case SyntaxKind.DisabledTextTrivia: { return LuaStatementSyntax.Empty; } case SyntaxKind.RegionDirectiveTrivia: case SyntaxKind.EndRegionDirectiveTrivia: { return new LuaShortCommentStatement(content); } default: throw new InvalidOperationException(); } } } private bool CheckInsertLuaCodeTemplate(string commentContent, out LuaStatementSyntax statement) { statement = null; char openBracket = LuaSyntaxNode.Tokens.OpenBracket[0]; int index = commentContent.IndexOf(openBracket); if (index != -1) { char equals = LuaSyntaxNode.Tokens.Equals[0]; int count = 0; ++index; while (commentContent[index] == equals) { ++index; ++count; } if (commentContent[index] == openBracket) { string closeToken = LuaSyntaxNode.Tokens.CloseBracket + new string(equals, count) + LuaSyntaxNode.Tokens.CloseBracket; int begin = index + 1; int end = commentContent.IndexOf(closeToken, begin); if (end != -1) { string codeString = commentContent[begin..end]; string[] lines = codeString.Split('\n'); var codeLines = new LuaStatementListSyntax(); int indent = -1; foreach (string line in lines) { if (!string.IsNullOrWhiteSpace(line)) { if (indent == -1) { indent = line.IndexOf(i => !char.IsWhiteSpace(i)); } int space = line.IndexOf(i => !char.IsWhiteSpace(i)); string code = space >= indent && indent != -1 ? line.Substring(indent) : line; codeLines.Statements.Add((LuaIdentifierNameSyntax)code); } } statement = codeLines; return true; } } } return false; } } private IEnumerable<LuaStatementSyntax> VisitTriviaAndNode(SyntaxNode rootNode, IEnumerable<CSharpSyntaxNode> nodes, bool isCheckBlank = true) { var syntaxTrivias = rootNode.DescendantTrivia().Where(i => i.IsExportSyntaxTrivia(rootNode)); var syntaxTriviaNodes = syntaxTrivias.Select(i => new BlockCommonNode(i)); List<BlockCommonNode> list = nodes.Select(i => new BlockCommonNode(i)).ToList(); bool hasComments = false; foreach (var comment in syntaxTriviaNodes) { bool isContains = list.Any(i => i.Contains(comment)); if (!isContains) { list.Add(comment); hasComments = true; } } if (hasComments) { list.Sort(); } int lastLine = -1; foreach (var common in list) { if (isCheckBlank) { var black = common.CheckBlankLine(ref lastLine); if (black != null) { yield return black; } } yield return (LuaStatementSyntax)common.Visit(this); } } public override LuaSyntaxNode VisitBlock(BlockSyntax node) { LuaBlockStatementSyntax block = new LuaBlockStatementSyntax(); PushBlock(block); var statements = VisitTriviaAndNode(node, node.Statements); block.Statements.AddRange(statements); var indexs = block.UsingDeclarations; if (indexs != null) { block.UsingDeclarations = null; ApplyUsingDeclarations(block, indexs, node); } PopBlock(); return block; } private LuaReturnStatementSyntax BuildLoopControlReturnStatement(LuaExpressionSyntax expression) { var returnStatement = new LuaReturnStatementSyntax(LuaIdentifierLiteralExpressionSyntax.True); if (expression != null) { returnStatement.Expressions.Add(expression); } return returnStatement; } private LuaStatementSyntax InternalVisitReturnStatement(LuaExpressionSyntax expression) { if (CurFunction is LuaCheckLoopControlExpressionSyntax check) { check.HasReturn = true; return BuildLoopControlReturnStatement(expression); } if (CurBlock.HasUsingDeclarations) { return BuildLoopControlReturnStatement(expression); } LuaStatementSyntax result; var curMethodInfo = CurMethodInfoOrNull; if (curMethodInfo != null && curMethodInfo.RefOrOutParameters.Count > 0) { if (curMethodInfo.IsInlining) { var multipleAssignment = new LuaMultipleAssignmentExpressionSyntax(); multipleAssignment.Lefts.AddRange(curMethodInfo.InliningReturnVars); if (expression != null) { multipleAssignment.Rights.Add(expression); } multipleAssignment.Rights.AddRange(curMethodInfo.RefOrOutParameters); result = multipleAssignment; } else { var returnStatement = new LuaReturnStatementSyntax(); if (expression != null) { returnStatement.Expressions.Add(expression); } returnStatement.Expressions.AddRange(curMethodInfo.RefOrOutParameters); result = returnStatement; } } else { if (curMethodInfo != null && curMethodInfo.IsInlining) { Contract.Assert(curMethodInfo.InliningReturnVars.Count == 1); result = curMethodInfo.InliningReturnVars.First().Assignment(expression); } else { result = new LuaReturnStatementSyntax(expression); } } return result; } public override LuaSyntaxNode VisitReturnStatement(ReturnStatementSyntax node) { var expression = node.Expression != null ? VisitExpression(node.Expression) : null; var result = InternalVisitReturnStatement(expression); if (node.Parent.IsKind(SyntaxKind.Block) && node.Parent.Parent is MemberDeclarationSyntax) { var block = (BlockSyntax)node.Parent; if (block.Statements.Last() != node) { var blockStatement = new LuaBlockStatementSyntax(); blockStatement.Statements.Add(result); result = blockStatement; } else if (expression == null) { result = LuaStatementSyntax.Empty; } } return result; } public override LuaSyntaxNode VisitExpressionStatement(ExpressionStatementSyntax node) { var expression = node.Expression.AcceptExpression(this); ReleaseTempIdentifiers(); if (expression != LuaExpressionSyntax.EmptyExpression) { if (expression is LuaLiteralExpressionSyntax) { return new LuaShortCommentExpressionStatement(expression); } return new LuaExpressionStatementSyntax(expression); } else { return LuaStatementSyntax.Empty; } } private LuaExpressionSyntax BuildCommonAssignmentExpression(LuaExpressionSyntax left, LuaExpressionSyntax right, string operatorToken, ExpressionSyntax rightNode, ExpressionSyntax parnet) { bool isPreventDebugConcatenation = IsPreventDebug && operatorToken == LuaSyntaxNode.Tokens.Concatenation; if (left is LuaPropertyAdapterExpressionSyntax propertyAdapter) { LuaExpressionSyntax expression = null; var geter = propertyAdapter.GetCloneOfGet(); LuaExpressionSyntax leftExpression = geter; if (isPreventDebugConcatenation) { leftExpression = new LuaInvocationExpressionSyntax(LuaIdentifierNameSyntax.SystemToString, leftExpression); } if (parnet != null) { expression = GetUserDefinedOperatorExpression(parnet, leftExpression, right); } if (expression == null) { expression = leftExpression.Binary(operatorToken, right); } propertyAdapter.ArgumentList.AddArgument(expression); return propertyAdapter; } else { LuaExpressionSyntax expression = null; LuaExpressionSyntax leftExpression = left; if (isPreventDebugConcatenation) { leftExpression = new LuaInvocationExpressionSyntax(LuaIdentifierNameSyntax.SystemToString, leftExpression); } if (parnet != null) { expression = GetUserDefinedOperatorExpression(parnet, leftExpression, right); } if (expression == null) { bool isRightParenthesized = rightNode is BinaryExpressionSyntax || rightNode.IsKind(SyntaxKind.ConditionalExpression); if (isRightParenthesized) { right = right.Parenthesized(); } expression = leftExpression.Binary(operatorToken, right); } return left.Assignment(expression); } } private LuaExpressionSyntax BuildCommonAssignmentExpression(ExpressionSyntax leftNode, ExpressionSyntax rightNode, string operatorToken, ExpressionSyntax parnet) { var left = VisitExpression(leftNode); var right = VisitExpression(rightNode); return BuildCommonAssignmentExpression(left, right, operatorToken, rightNode, parnet); } private LuaExpressionSyntax BuildDelegateBinaryExpression(LuaExpressionSyntax left, LuaExpressionSyntax right, bool isPlus) { if (IsPreventDebug) { var methodName = isPlus ? LuaIdentifierNameSyntax.DelegateCombine : LuaIdentifierNameSyntax.DelegateRemove; return new LuaInvocationExpressionSyntax(methodName, left, right); } else { var operatorToken = isPlus ? LuaSyntaxNode.Tokens.Plus : LuaSyntaxNode.Tokens.Sub; return left.Binary(operatorToken, right); } } private LuaExpressionSyntax BuildDelegateAssignmentExpression(LuaExpressionSyntax left, LuaExpressionSyntax right, bool isPlus) { if (left is LuaPropertyAdapterExpressionSyntax propertyAdapter) { if (propertyAdapter.IsProperty) { propertyAdapter.ArgumentList.AddArgument(BuildDelegateBinaryExpression(propertyAdapter.GetCloneOfGet(), right, isPlus)); return propertyAdapter; } else { propertyAdapter.IsGetOrAdd = isPlus; propertyAdapter.ArgumentList.AddArgument(right); return propertyAdapter; } } else { return left.Assignment(BuildDelegateBinaryExpression(left, right, isPlus)); } } private LuaExpressionSyntax BuildBinaryInvokeAssignmentExpression(LuaExpressionSyntax left, LuaExpressionSyntax right, LuaExpressionSyntax methodName) { if (left is LuaPropertyAdapterExpressionSyntax propertyAdapter) { var invocation = new LuaInvocationExpressionSyntax(methodName, propertyAdapter.GetCloneOfGet(), right); propertyAdapter.ArgumentList.AddArgument(invocation); return propertyAdapter; } else { var invocation = new LuaInvocationExpressionSyntax(methodName, left, right); return left.Assignment(invocation); } } private LuaExpressionSyntax BuildBinaryInvokeAssignmentExpression(ExpressionSyntax leftNode, ExpressionSyntax rightNode, LuaExpressionSyntax methodName) { var left = leftNode.AcceptExpression(this); var right = rightNode.AcceptExpression(this); return BuildBinaryInvokeAssignmentExpression(left, right, methodName); } private LuaExpressionSyntax BuildLuaSimpleAssignmentExpression(LuaExpressionSyntax left, LuaExpressionSyntax right) { if (left is LuaPropertyAdapterExpressionSyntax propertyAdapter) { propertyAdapter.IsGetOrAdd = false; propertyAdapter.ArgumentList.AddArgument(right); return propertyAdapter; } else { return left.Assignment(right); } } private List<LuaExpressionSyntax> BuildNumberNullableIdentifiers(ref LuaExpressionSyntax left, ref LuaExpressionSyntax right, bool isLeftNullbale, bool isRightNullable) { var identifiers = new List<LuaExpressionSyntax>(); if (isLeftNullbale) { if (isRightNullable) { left = BuildNullableExpressionIdentifier(left, identifiers); right = BuildNullableExpressionIdentifier(right, identifiers); } else { left = BuildNullableExpressionIdentifier(left, identifiers); } } else { right = BuildNullableExpressionIdentifier(right, identifiers); } return identifiers; } private static void TransformIdentifiersForCompareExpression(List<LuaExpressionSyntax> identifiers) { for (int i = 0; i < identifiers.Count; ++i) { var identifier = identifiers[i]; identifiers[i] = identifier.NotEquals(LuaIdentifierNameSyntax.Nil); } } private static void CheckNumberNullableCompareExpression(string operatorToken, List<LuaExpressionSyntax> identifiers) { switch (operatorToken) { case ">": case ">=": case "<": case "<=": { TransformIdentifiersForCompareExpression(identifiers); break; } } } private LuaExpressionSyntax BuildNumberNullableExpression(LuaExpressionSyntax left, LuaExpressionSyntax right, string operatorToken, bool isLeftNullbale, bool isRightNullable, LuaIdentifierNameSyntax method) { if (left.IsNil() || right.IsNil()) { return LuaIdentifierLiteralExpressionSyntax.Nil; } var identifiers = BuildNumberNullableIdentifiers(ref left, ref right, isLeftNullbale, isRightNullable); LuaExpressionSyntax expression; if (method != null) { expression = new LuaInvocationExpressionSyntax(method, left, right); } else { expression = left.Binary(operatorToken, right); CheckNumberNullableCompareExpression(operatorToken, identifiers); } return identifiers.Aggregate((x, y) => x.And(y)).And(expression); } private LuaExpressionSyntax BuildNumberNullableAssignment(LuaExpressionSyntax left, LuaExpressionSyntax right, string operatorToken, bool isLeftNullbale, bool isRightNullable, LuaIdentifierNameSyntax method) { if (left is LuaPropertyAdapterExpressionSyntax propertyAdapter) { Contract.Assert(propertyAdapter.IsProperty); propertyAdapter.ArgumentList.AddArgument(BuildNumberNullableExpression(propertyAdapter.GetCloneOfGet(), right, operatorToken, isLeftNullbale, isRightNullable, method)); return propertyAdapter; } else { return left.Assignment(BuildNumberNullableExpression(left, right, operatorToken, isLeftNullbale, isRightNullable, method)); } } private bool IsNullableType(ExpressionSyntax leftNode, ExpressionSyntax rightNode, out bool isLeftNullable, out bool isRightNullable) { var leftType = semanticModel_.GetTypeInfo(leftNode).Type; var rightType = semanticModel_.GetTypeInfo(rightNode).Type; isLeftNullable = leftType != null && leftType.IsNullableType(); isRightNullable = rightType != null && rightType.IsNullableType(); return isLeftNullable || isRightNullable; } private bool IsNullableType(ExpressionSyntax leftNode, ExpressionSyntax rightNode) => IsNullableType(leftNode, rightNode, out _, out _); private bool IsNullableAssignmentExpression(ExpressionSyntax left, ExpressionSyntax right, string operatorToken, out LuaExpressionSyntax result, LuaIdentifierNameSyntax method = null) { if (IsNullableType(left, right, out bool isLeftNullbale, out bool isRightNullable)) { var leftExpression = left.AcceptExpression(this); var rightExpression = right.AcceptExpression(this); result = BuildNumberNullableAssignment(leftExpression, rightExpression, operatorToken, isLeftNullbale, isRightNullable, method); return true; } result = null; return false; } private bool IsNumberNullableAssignmentExpression(INamedTypeSymbol containingType, ExpressionSyntax left, ExpressionSyntax right, string operatorToken, out LuaExpressionSyntax result, LuaIdentifierNameSyntax method = null) { if (containingType.IsNumberType(false)) { if (IsNullableAssignmentExpression(left, right, operatorToken, out result, method)) { return true; } } result = null; return false; } private LuaExpressionSyntax BuildNumberAssignmentExpression(ExpressionSyntax node, ExpressionSyntax leftNode, ExpressionSyntax rightNode, SyntaxKind kind) { if (semanticModel_.GetSymbolInfo(node).Symbol is IMethodSymbol symbol) { var containingType = symbol.ContainingType; if (containingType != null) { switch (kind) { case SyntaxKind.AddAssignmentExpression: case SyntaxKind.SubtractAssignmentExpression: { if (containingType.IsStringType()) { var left = leftNode.AcceptExpression(this); var right = WrapStringConcatExpression(rightNode); return BuildCommonAssignmentExpression(left, right, LuaSyntaxNode.Tokens.Concatenation, rightNode, null); } bool isPlus = kind == SyntaxKind.AddAssignmentExpression; if (containingType.IsDelegateType() || (symbol.MethodKind == MethodKind.EventAdd || symbol.MethodKind == MethodKind.EventRemove)) { var left = leftNode.AcceptExpression(this); var right = rightNode.AcceptExpression(this); return BuildDelegateAssignmentExpression(left, right, isPlus); } if (IsPreventDebug) { if (IsNumberNullableAssignmentExpression(containingType, leftNode, rightNode, isPlus ? LuaSyntaxNode.Tokens.Plus : LuaSyntaxNode.Tokens.Sub, out var result)) { return result; } } break; } case SyntaxKind.MultiplyAssignmentExpression: { if (IsNumberNullableAssignmentExpression(containingType, leftNode, rightNode, LuaSyntaxNode.Tokens.Multiply, out var result)) { return result; } break; } case SyntaxKind.DivideAssignmentExpression: { if (IsPreventDebug && containingType.IsDoubleOrFloatType(false)) { if (IsNullableAssignmentExpression(leftNode, rightNode, LuaSyntaxNode.Tokens.Div, out var result)) { return result; } } if (containingType.IsIntegerType(false)) { if (IsNullableType(leftNode, rightNode)) { if (IsLuaClassic || IsPreventDebug) { bool success = IsNullableAssignmentExpression(leftNode, rightNode, null, out var result, LuaIdentifierNameSyntax.IntegerDiv); Contract.Assert(success); return result; } } return BuildBinaryInvokeAssignmentExpression(leftNode, rightNode, LuaIdentifierNameSyntax.IntegerDiv); } break; } case SyntaxKind.ModuloAssignmentExpression: { if (containingType.IsNumberType(false)) { if (IsLuaClassic) { var method = containingType.IsIntegerType(false) ? LuaIdentifierNameSyntax.Mod : LuaIdentifierNameSyntax.ModFloat; if (IsNullableAssignmentExpression(leftNode, rightNode, null, out var result, method)) { return result; } return BuildBinaryInvokeAssignmentExpression(leftNode, rightNode, method); } else { if (IsPreventDebug && IsNullableAssignmentExpression(leftNode, rightNode, null, out var result, LuaIdentifierNameSyntax.Mod)) { return result; } return BuildBinaryInvokeAssignmentExpression(leftNode, rightNode, LuaIdentifierNameSyntax.Mod); } } break; } case SyntaxKind.LeftShiftAssignmentExpression: case SyntaxKind.RightShiftAssignmentExpression: { if (containingType.IsIntegerType(false)) { bool isLeftShift = kind == SyntaxKind.LeftShiftAssignmentExpression; if (IsLuaClassic) { var method = isLeftShift ? LuaIdentifierNameSyntax.ShiftLeft : LuaIdentifierNameSyntax.ShiftRight; if (IsNullableAssignmentExpression(leftNode, rightNode, null, out var result, method)) { return result; } return BuildBinaryInvokeAssignmentExpression(leftNode, rightNode, method); } else if (IsPreventDebug && IsNullableAssignmentExpression(leftNode, rightNode, isLeftShift ? LuaSyntaxNode.Tokens.ShiftLeft : LuaSyntaxNode.Tokens.ShiftRight, out var result)) { return result; } } break; } } } } return null; } private LuaExpressionSyntax BuildLuaAssignmentExpression(AssignmentExpressionSyntax node, ExpressionSyntax leftNode, ExpressionSyntax rightNode, SyntaxKind kind) { LuaExpressionSyntax resultExpression = null; switch (kind) { case SyntaxKind.SimpleAssignmentExpression: { var left = leftNode.AcceptExpression(this); var right = VisitExpression(rightNode); if (leftNode.Kind().IsTupleDeclaration()) { if (!rightNode.IsKind(SyntaxKind.TupleExpression)) { right = BuildDeconstructExpression(rightNode, right); } } else if (leftNode.IsKind(SyntaxKind.IdentifierName) && left == LuaIdentifierNameSyntax.Placeholder) { var local = new LuaLocalVariableDeclaratorSyntax(LuaIdentifierNameSyntax.Placeholder, right); CurBlock.AddStatement(local); return LuaExpressionSyntax.EmptyExpression; } else if (leftNode.IsKind(SyntaxKind.ThisExpression)) { return left.MemberAccess(LuaIdentifierNameSyntax.CopyThis, true).Invocation(right); } return BuildLuaSimpleAssignmentExpression(left, right); } case SyntaxKind.AddAssignmentExpression: case SyntaxKind.SubtractAssignmentExpression: case SyntaxKind.MultiplyAssignmentExpression: case SyntaxKind.DivideAssignmentExpression: case SyntaxKind.ModuloAssignmentExpression: case SyntaxKind.LeftShiftAssignmentExpression: case SyntaxKind.RightShiftAssignmentExpression: resultExpression = BuildNumberAssignmentExpression(node, leftNode, rightNode, kind); break; case SyntaxKind.AndAssignmentExpression: { resultExpression = BuildBitAssignmentExpression(leftNode, rightNode, LuaSyntaxNode.Tokens.And, LuaIdentifierNameSyntax.BitAnd, node); break; } case SyntaxKind.ExclusiveOrAssignmentExpression: { resultExpression = BuildBitAssignmentExpression(leftNode, rightNode, LuaSyntaxNode.Tokens.NotEquals, LuaIdentifierNameSyntax.BitXor, node); break; } case SyntaxKind.OrAssignmentExpression: { resultExpression = BuildBitAssignmentExpression(leftNode, rightNode, LuaSyntaxNode.Tokens.Or, LuaIdentifierNameSyntax.BitOr, node); break; } case SyntaxKind.CoalesceAssignmentExpression: { var left = leftNode.AcceptExpression(this); var right = VisitExpression(rightNode); var ifStatement = new LuaIfStatementSyntax(left.EqualsEquals(LuaIdentifierNameSyntax.Nil)); ifStatement.Body.AddStatement(left.Assignment(right)); CurBlock.AddStatement(ifStatement); return LuaExpressionSyntax.EmptyExpression; } } if (resultExpression != null) { return resultExpression; } string operatorToken = GetOperatorToken(node.OperatorToken.ValueText[0 ..^1]); return BuildCommonAssignmentExpression(leftNode, rightNode, operatorToken, node); } private LuaIdentifierNameSyntax BuildBoolXorOfNullAssignmentExpression(LuaExpressionSyntax left, LuaExpressionSyntax right, bool isLeftNullable, bool isRightNullable) { var temp = GetTempIdentifier(); CurBlock.AddStatement(new LuaLocalVariableDeclaratorSyntax(temp)); var identifiers = BuildNumberNullableIdentifiers(ref left, ref right, isLeftNullable, isRightNullable); LuaExpressionSyntax condition; if (identifiers.Count == 1) { condition = identifiers.First().NotEquals(LuaIdentifierNameSyntax.Nil); } else { condition = left.NotEquals(LuaIdentifierNameSyntax.Nil).And(right.NotEquals(LuaIdentifierNameSyntax.Nil)); } var ifStatement = new LuaIfStatementSyntax(condition); ifStatement.Body.AddStatement(temp.Assignment(left.NotEquals(right))); CurBlock.AddStatement(ifStatement); return temp; } private LuaExpressionSyntax BuildBoolXorOfNullAssignmentExpression(ExpressionSyntax leftNode, ExpressionSyntax rightNode, bool isLeftNullable, bool isRightNullable) { var left = VisitExpression(leftNode); var right = VisitExpression(rightNode); LuaExpressionSyntax result; if (right.IsNil()) { result = new LuaConstLiteralExpression(LuaIdentifierLiteralExpressionSyntax.Nil, rightNode.ToString()); } else if (left is LuaPropertyAdapterExpressionSyntax propertyAdapter) { result = BuildBoolXorOfNullAssignmentExpression(propertyAdapter.GetCloneOfGet(), right, isLeftNullable, isRightNullable); } else { result = BuildBoolXorOfNullAssignmentExpression(left, right, isLeftNullable, isRightNullable); } return BuildLuaSimpleAssignmentExpression(left, result); } private LuaExpressionSyntax BuildLeftNullableBoolLogicAssignmentExpression(ExpressionSyntax leftNode, ExpressionSyntax rightNode, string boolOperatorToken) { var left = VisitExpression(leftNode); var right = VisitExpression(rightNode); var temp = GetTempIdentifier(); LuaExpressionSyntax identifier; CurBlock.AddStatement(new LuaLocalVariableDeclaratorSyntax(temp)); if (left is LuaPropertyAdapterExpressionSyntax propertyAdapter) { var geter = propertyAdapter.GetCloneOfGet(); identifier = BuildNullableExpressionIdentifier(geter, new List<LuaExpressionSyntax>()); } else { identifier = BuildNullableExpressionIdentifier(left, new List<LuaExpressionSyntax>()); } var ifStatement = new LuaIfStatementSyntax(identifier.EqualsEquals(LuaIdentifierNameSyntax.Nil)); ifStatement.Body.AddStatement(temp.Assignment(right.Binary(boolOperatorToken, identifier))); ifStatement.Else = new LuaElseClauseSyntax(); ifStatement.Else.Body.AddStatement(temp.Assignment(identifier.Binary(boolOperatorToken, right))); CurBlock.AddStatement(ifStatement); return BuildLuaSimpleAssignmentExpression(left, temp); } private LuaExpressionSyntax BuildBitAssignmentExpression(ExpressionSyntax leftNode, ExpressionSyntax rightNode, string boolOperatorToken, LuaIdentifierNameSyntax methodName, ExpressionSyntax parnet) { if (semanticModel_.GetSymbolInfo(parnet).Symbol is IMethodSymbol symbol) { var containingType = symbol.ContainingType; if (containingType != null) { if (containingType.IsBoolType(false)) { switch (parnet.Kind()) { case SyntaxKind.ExclusiveOrAssignmentExpression: { if (IsNullableType(leftNode, rightNode, out bool isLeftNullable, out bool isRightNullable)) { return BuildBoolXorOfNullAssignmentExpression(leftNode, rightNode, isLeftNullable, isRightNullable); } break; } case SyntaxKind.AndAssignmentExpression: case SyntaxKind.OrAssignmentExpression: { if (IsNullableType(leftNode, rightNode, out bool isLeftNullable, out _) && isLeftNullable) { return BuildLeftNullableBoolLogicAssignmentExpression(leftNode, rightNode, boolOperatorToken); } break; } } return BuildCommonAssignmentExpression(leftNode, rightNode, boolOperatorToken, null); } if (containingType.IsIntegerType(false) || containingType.TypeKind == TypeKind.Enum) { if (IsLuaClassic) { if (IsNullableAssignmentExpression(leftNode, rightNode, null, out var result, methodName)) { return result; } return BuildBinaryInvokeAssignmentExpression(leftNode, rightNode, methodName); } else if (IsPreventDebug && IsNullableAssignmentExpression(leftNode, rightNode, null, out var result, methodName)) { return result; } } } } return null; } private LuaExpressionSyntax InternalVisitAssignmentExpression(AssignmentExpressionSyntax node) { List<LuaExpressionSyntax> assignments = new List<LuaExpressionSyntax>(); while (true) { var leftExpression = node.Left; var rightExpression = node.Right; var kind = node.Kind(); if (rightExpression is AssignmentExpressionSyntax assignmentRight) { assignments.Add(BuildLuaAssignmentExpression(node, leftExpression, assignmentRight.Left, kind)); node = assignmentRight; } else { assignments.Add(BuildLuaAssignmentExpression(node, leftExpression, rightExpression, kind)); break; } } if (assignments.Count == 1) { return assignments.First(); } else { assignments.Reverse(); LuaLineMultipleExpressionSyntax multipleAssignment = new LuaLineMultipleExpressionSyntax(); multipleAssignment.Assignments.AddRange(assignments); return multipleAssignment; } } private bool IsInlineAssignment(AssignmentExpressionSyntax node) { bool isInlineAssignment = false; SyntaxKind kind = node.Parent.Kind(); switch (kind) { case SyntaxKind.ExpressionStatement: case SyntaxKind.ForStatement: break; case SyntaxKind.ArrowExpressionClause: { var symbol = semanticModel_.GetDeclaredSymbol(node.Parent.Parent); switch (symbol.Kind) { case SymbolKind.Method: var method = (IMethodSymbol)symbol; if (!method.ReturnsVoid) { isInlineAssignment = true; } break; case SymbolKind.Property: { var property = (IPropertySymbol)symbol; if (!property.GetMethod.ReturnsVoid) { isInlineAssignment = true; } break; } } break; } case SyntaxKind.SimpleLambdaExpression: case SyntaxKind.ParenthesizedLambdaExpression: { var method = CurMethodInfoOrNull.Symbol; if (!method.ReturnsVoid) { isInlineAssignment = true; } break; } default: isInlineAssignment = true; break; } return isInlineAssignment; } public override LuaSyntaxNode VisitAssignmentExpression(AssignmentExpressionSyntax node) { var assignment = InternalVisitAssignmentExpression(node); if (IsInlineAssignment(node)) { CurBlock.Statements.Add(assignment); if (assignment is LuaLineMultipleExpressionSyntax lineMultipleExpression) { assignment = lineMultipleExpression.Assignments.Last(); } if (assignment is LuaAssignmentExpressionSyntax assignmentExpression) { assignment = assignmentExpression.Left; } else { assignment = node.Left.AcceptExpression(this); } } return assignment; } private sealed class RefOrOutArgument { public LuaExpressionSyntax Expression { get; } public bool IsDeclaration { get; } public bool IsSpecial { get; } public RefOrOutArgument(LuaExpressionSyntax expression) { Expression = expression; } public RefOrOutArgument(LuaExpressionSyntax expression, ArgumentSyntax argument) { Expression = expression; IsSpecial = IsInSpecialBinaryExpression(argument); IsDeclaration = (argument.Expression.IsKind(SyntaxKind.DeclarationExpression) && !IsSpecial) || expression == LuaIdentifierNameSyntax.Placeholder; } private static bool IsInSpecialBinaryExpression(ArgumentSyntax argument) { if (argument.Expression.IsKind(SyntaxKind.DeclarationExpression)) { var invocationExpression = (InvocationExpressionSyntax)argument.Parent.Parent; var parent = invocationExpression.Parent; if (parent.IsKind(SyntaxKind.LogicalAndExpression) || parent.IsKind(SyntaxKind.LogicalOrExpression)) { var binaryExpression = (BinaryExpressionSyntax)parent; if (binaryExpression.Right == invocationExpression) { return true; } } } return false; } } private LuaExpressionSyntax BuildInvokeRefOrOut(CSharpSyntaxNode node, LuaExpressionSyntax invocation, IEnumerable<RefOrOutArgument> refOrOutArguments) { var locals = new LuaLocalVariablesSyntax(); var multipleAssignment = new LuaMultipleAssignmentExpressionSyntax(); var propertyStatements = new LuaStatementListSyntax(); void FillRefOrOutArguments() { foreach (var refOrOutArgument in refOrOutArguments) { // fn(out arr[0]) if (refOrOutArgument.Expression is LuaPropertyAdapterExpressionSyntax propertyAdapter) { var propertyTemp = GetTempIdentifier(); locals.Variables.Add(propertyTemp); multipleAssignment.Lefts.Add(propertyTemp); var setPropertyAdapter = propertyAdapter.GetClone(); setPropertyAdapter.IsGetOrAdd = false; setPropertyAdapter.ArgumentList.AddArgument(propertyTemp); propertyStatements.Statements.Add(setPropertyAdapter); } else { if (refOrOutArgument.IsDeclaration) { locals.Variables.Add((LuaIdentifierNameSyntax)refOrOutArgument.Expression); } else if (refOrOutArgument.IsSpecial) { CurFunction.Body.AddHeadVariable((LuaIdentifierNameSyntax)refOrOutArgument.Expression); } multipleAssignment.Lefts.Add(refOrOutArgument.Expression); } } } switch (node.Parent.Kind()) { case SyntaxKind.ExpressionStatement: case SyntaxKind.ConstructorDeclaration: { var symbol = (IMethodSymbol)semanticModel_.GetSymbolInfo(node).Symbol; if (!symbol.ReturnsVoid || node.IsKind(SyntaxKind.ObjectCreationExpression)) { var temp = node.Parent.IsKind(SyntaxKind.ExpressionStatement) ? LuaIdentifierNameSyntax.Placeholder : GetTempIdentifier(); locals.Variables.Add(temp); multipleAssignment.Lefts.Add(temp); } FillRefOrOutArguments(); multipleAssignment.Rights.Add(invocation); if (locals.Variables.Count > 0) { CurBlock.Statements.Add(locals); if (locals.Variables.SequenceEqual(multipleAssignment.Lefts)) { locals.Initializer = new LuaEqualsValueClauseListSyntax(multipleAssignment.Rights); if (propertyStatements.Statements.Count > 0) { CurBlock.Statements.Add(propertyStatements); } return LuaExpressionSyntax.EmptyExpression; } } if (propertyStatements.Statements.Count > 0) { CurBlock.Statements.Add(multipleAssignment); CurBlock.Statements.Add(propertyStatements); return LuaExpressionSyntax.EmptyExpression; } else { return multipleAssignment; } } default: { var temp = GetTempIdentifier(); locals.Variables.Add(temp); multipleAssignment.Lefts.Add(temp); FillRefOrOutArguments(); multipleAssignment.Rights.Add(invocation); CurBlock.Statements.Add(locals); if (locals.Variables.SequenceEqual(multipleAssignment.Lefts)) { locals.Initializer = new LuaEqualsValueClauseListSyntax(multipleAssignment.Rights); } else { CurBlock.Statements.Add(multipleAssignment); } if (propertyStatements.Statements.Count > 0) { CurBlock.Statements.Add(propertyStatements); } return temp; } } } private bool IsEnumToStringInvocationExpression(IMethodSymbol symbol, InvocationExpressionSyntax node, out LuaExpressionSyntax result) { result = null; if (symbol.Name == "ToString") { if (symbol.ContainingType.SpecialType == SpecialType.System_Enum) { var memberAccessExpression = (MemberAccessExpressionSyntax)node.Expression; var target = memberAccessExpression.Expression.AcceptExpression(this); var enumTypeSymbol = semanticModel_.GetTypeInfo(memberAccessExpression.Expression).Type; result = BuildEnumToStringExpression(enumTypeSymbol, false, target, memberAccessExpression.Expression); return true; } else if (symbol.ContainingType.IsEnumType(out var enumTypeSymbol, out bool isNullable)) { var memberAccessExpression = (MemberAccessExpressionSyntax)node.Expression; var target = memberAccessExpression.Expression.AcceptExpression(this); result = BuildEnumToStringExpression(enumTypeSymbol, isNullable, target, memberAccessExpression.Expression); return true; } } return false; } private List<Func<LuaExpressionSyntax>> FillCodeTemplateInvocationArguments(IMethodSymbol symbol, ArgumentListSyntax argumentList, List<Func<LuaExpressionSyntax>> argumentExpressions) { argumentExpressions ??= new(); foreach (var argument in argumentList.Arguments) { if (argument.NameColon != null) { string name = argument.NameColon.Name.Identifier.ValueText; int index = symbol.Parameters.IndexOf(i => i.Name == name); if (index == -1) { throw new InvalidOperationException(); } argumentExpressions.AddAt(index, () => VisitExpression(argument.Expression)); } else { argumentExpressions.Add(() => VisitExpression(argument.Expression)); } } for (int i = 0; i < argumentExpressions.Count; ++i) { if (argumentExpressions[i] == null) { argumentExpressions[i] = () => GetDefaultParameterValue(symbol.Parameters[i], argumentList.Parent, true); } } if (symbol.Parameters.Length > argumentList.Arguments.Count) { argumentExpressions.AddRange(symbol.Parameters.Skip(argumentList.Arguments.Count).Where(i => !i.IsParams).Select(i => { Func<LuaExpressionSyntax> func = () => GetDefaultParameterValue(i, argumentList.Parent, true); return func; })); } return argumentExpressions; } private LuaExpressionSyntax CheckCodeTemplateInvocationExpression(IMethodSymbol symbol, InvocationExpressionSyntax node) { var kind = node.Expression.Kind(); if (kind == SyntaxKind.SimpleMemberAccessExpression || kind == SyntaxKind.MemberBindingExpression || kind == SyntaxKind.IdentifierName) { if (IsEnumToStringInvocationExpression(symbol, node, out var result)) { return result; } string codeTemplate = XmlMetaProvider.GetMethodCodeTemplate(symbol); if (codeTemplate != null) { var argumentExpressions = new List<Func<LuaExpressionSyntax>>(); var memberAccessExpression = node.Expression as MemberAccessExpressionSyntax; if (symbol.IsExtensionMethod) { if (symbol.ReducedFrom != null) { if (memberAccessExpression != null) { argumentExpressions.Add(() => memberAccessExpression.Expression.AcceptExpression(this)); } else { Contract.Assert(kind == SyntaxKind.MemberBindingExpression); argumentExpressions.Add(() => conditionalTemps_.Peek()); } } if (symbol.ContainingType.IsSystemLinqEnumerable()) { CurCompilationUnit.ImportLinq(); } } FillCodeTemplateInvocationArguments(symbol, node.ArgumentList, argumentExpressions); var invocationExpression = InternalBuildCodeTemplateExpression( codeTemplate, memberAccessExpression?.Expression, argumentExpressions, symbol.TypeArguments, kind == SyntaxKind.MemberBindingExpression ? conditionalTemps_.Peek() : null); var refOrOuts = node.ArgumentList.Arguments.Where(i => i.RefKindKeyword.IsOutOrRef()); if (refOrOuts.Any()) { var refOrOutArguments = refOrOuts.Select(i => { var argument = i.AcceptExpression(this); return new RefOrOutArgument(argument, i); }); return BuildInvokeRefOrOut(node, invocationExpression, refOrOutArguments); } else { return invocationExpression; } } } return null; } private List<LuaExpressionSyntax> BuildInvocationArguments(IMethodSymbol symbol, InvocationExpressionSyntax node, out List<RefOrOutArgument> refOrOutArguments) { refOrOutArguments = new List<RefOrOutArgument>(); List<LuaExpressionSyntax> arguments; if (symbol != null) { arguments = BuildArgumentList(symbol, symbol.Parameters, node.ArgumentList, refOrOutArguments); bool ignoreGeneric = generator_.XmlMetaProvider.IsMethodIgnoreGeneric(symbol); if (!ignoreGeneric) { if (symbol.MethodKind == MethodKind.DelegateInvoke) { foreach (var typeArgument in symbol.ContainingType.TypeArguments) { if (typeArgument.TypeKind == TypeKind.TypeParameter) { LuaExpressionSyntax typeName = GetTypeName(typeArgument); arguments.Add(typeName); } } } else { foreach (var typeArgument in symbol.TypeArguments) { LuaExpressionSyntax typeName = GetTypeName(typeArgument); arguments.Add(typeName); } } } TryRemoveNilArgumentsAtTail(symbol, arguments); } else { arguments = new List<LuaExpressionSyntax>(); foreach (var argument in node.ArgumentList.Arguments) { if (argument.NameColon != null) { throw new CompilationErrorException(argument, "named argument is not support at dynamic"); } FillInvocationArgument(arguments, argument, ImmutableArray<IParameterSymbol>.Empty, refOrOutArguments); } } return arguments; } private LuaInvocationExpressionSyntax CheckInvocationExpression(IMethodSymbol symbol, LuaExpressionSyntax expression) { LuaInvocationExpressionSyntax invocation; if (symbol != null && symbol.IsExtensionMethod) { if (expression is LuaMemberAccessExpressionSyntax memberAccess) { if (memberAccess.Name is LuaInternalMethodExpressionSyntax) { invocation = new LuaInvocationExpressionSyntax(memberAccess.Name); invocation.AddArgument(memberAccess.Expression); } else if (symbol.ReducedFrom != null) { invocation = BuildExtensionMethodInvocation(symbol.ReducedFrom, memberAccess.Expression); } else { invocation = new LuaInvocationExpressionSyntax(expression); } } else { invocation = new LuaInvocationExpressionSyntax(expression); } } else { if (expression is LuaMemberAccessExpressionSyntax memberAccess) { if (memberAccess.Name is LuaInternalMethodExpressionSyntax) { invocation = new LuaInvocationExpressionSyntax(memberAccess.Name); invocation.AddArgument(memberAccess.Expression); } else { invocation = new LuaInvocationExpressionSyntax(memberAccess); if (IsPreventDebug && symbol != null && !symbol.IsStatic) { var containingType = symbol.ContainingType; if (containingType.IsBasicType()) { var typeName = GetTypeName(containingType); invocation = typeName.MemberAccess(memberAccess.Name).Invocation(memberAccess.Expression); } else if (containingType.SpecialType == SpecialType.System_Object || containingType.IsBasicTypInterface()) { var methodMemberAccess = LuaIdentifierNameSyntax.System.MemberAccess(new LuaCodeTemplateExpressionSyntax(symbol.ContainingType.Name, memberAccess.Name)); invocation = methodMemberAccess.Invocation(memberAccess.Expression); } } } } else { invocation = new LuaInvocationExpressionSyntax(expression); if (expression is LuaInternalMethodExpressionSyntax) { if (!symbol.IsStatic) { invocation.AddArgument(LuaIdentifierNameSyntax.This); } } } } return invocation; } public override LuaSyntaxNode VisitInvocationExpression(InvocationExpressionSyntax node) { var constExpression = GetConstExpression(node); if (constExpression != null) { return constExpression; } var symbol = (IMethodSymbol)semanticModel_.GetSymbolInfo(node).Symbol; if (symbol != null) { if (symbol.ReturnsVoid) { if (generator_.IsConditionalAttributeIgnore(symbol) || symbol.IsEmptyPartialMethod()) { return LuaExpressionSyntax.EmptyExpression; } } var codeTemplateExpression = CheckCodeTemplateInvocationExpression(symbol, node); if (codeTemplateExpression != null) { return codeTemplateExpression; } } var arguments = BuildInvocationArguments(symbol, node, out var refOrOutArguments); var expression = node.Expression.AcceptExpression(this); var invocation = CheckInvocationExpression(symbol, expression); invocation.AddArguments(arguments); LuaExpressionSyntax resultExpression = invocation; if (symbol != null && symbol.HasAggressiveInliningAttribute()) { if (InliningInvocationExpression(node, symbol, invocation, out var inlineExpression)) { resultExpression = inlineExpression; } } if (refOrOutArguments.Count > 0) { resultExpression = BuildInvokeRefOrOut(node, resultExpression, refOrOutArguments); } return resultExpression; } private LuaInvocationExpressionSyntax BuildExtensionMethodInvocation(IMethodSymbol reducedFrom, LuaExpressionSyntax expression) { var typeName = GetTypeName(reducedFrom.ContainingType); var methodName = GetMemberName(reducedFrom); return typeName.MemberAccess(methodName).Invocation(expression); } private LuaExpressionSyntax GetDefaultParameterValue(IParameterSymbol parameter, SyntaxNode node, bool isCheckCallerAttribute) { Contract.Assert(parameter.HasExplicitDefaultValue); LuaExpressionSyntax defaultValue = isCheckCallerAttribute ? CheckCallerAttribute(parameter, node) : null; if (defaultValue == null) { if (parameter.ExplicitDefaultValue == null && parameter.Type.IsValueType) { defaultValue = GetDefaultValueExpression(parameter.Type); } else { defaultValue = GetLiteralExpression(parameter.ExplicitDefaultValue); } } Contract.Assert(defaultValue != null); return defaultValue; } private void CheckInvocationDefaultArguments( ISymbol symbol, ImmutableArray<IParameterSymbol> parameters, List<LuaExpressionSyntax> arguments, List<(NameColonSyntax Name, ExpressionSyntax Expression)> argumentNodeInfos, SyntaxNode node, bool isCheckCallerAttribute) { if (parameters.Length > arguments.Count) { var optionalParameters = parameters.Skip(arguments.Count); foreach (IParameterSymbol parameter in optionalParameters) { if (parameter.IsParams) { var arrayType = (IArrayTypeSymbol)parameter.Type; var elementType = GetTypeName(arrayType.ElementType); arguments.Add(LuaIdentifierNameSyntax.EmptyArray.Invocation(elementType)); } else { LuaExpressionSyntax defaultValue = GetDefaultParameterValue(parameter, node, isCheckCallerAttribute); arguments.Add(defaultValue); } } } else if (!parameters.IsEmpty) { IParameterSymbol last = parameters.Last(); if (last.IsParams && generator_.IsFromLuaModule(symbol) && !symbol.HasParamsAttribute()) { if (parameters.Length == arguments.Count) { var paramsArgument = argumentNodeInfos.Last(); if (paramsArgument.Name != null) { string name = paramsArgument.Name.Name.Identifier.ValueText; if (name != last.Name) { paramsArgument = argumentNodeInfos.First(i => i.Name != null && i.Name.Name.Identifier.ValueText == last.Name); } } var paramsType = semanticModel_.GetTypeInfo(paramsArgument.Expression).Type; bool isLastParamsArrayType = paramsType != null && paramsType.TypeKind == TypeKind.Array; if (!isLastParamsArrayType) { var arrayTypeSymbol = (IArrayTypeSymbol)last.Type; var array = BuildArray(arrayTypeSymbol.ElementType, arguments.Last()); arguments[^1] = array; } } else { int otherParameterCount = parameters.Length - 1; var arrayTypeSymbol = (IArrayTypeSymbol)last.Type; var paramsArguments = arguments.Skip(otherParameterCount).ToArray(); var array = BuildArray(arrayTypeSymbol.ElementType, paramsArguments); arguments.RemoveRange(otherParameterCount, arguments.Count - otherParameterCount); arguments.Add(array); } } } for (int i = 0; i < arguments.Count; ++i) { if (arguments[i] == null) { LuaExpressionSyntax defaultValue = GetDefaultParameterValue(parameters[i], node, isCheckCallerAttribute); arguments[i] = defaultValue; } } } private void CheckInvocationDefaultArguments(ISymbol symbol, ImmutableArray<IParameterSymbol> parameters, List<LuaExpressionSyntax> arguments, BaseArgumentListSyntax node) { var argumentNodeInfos = node.Arguments.Select(i => (i.NameColon, i.Expression)).ToList(); CheckInvocationDefaultArguments(symbol, parameters, arguments, argumentNodeInfos, node.Parent, true); } private void CheckPrevIsInvokeStatement(ExpressionSyntax node) { SyntaxNode current = node; while (true) { var parent = current.Parent; if (parent == null) { return; } switch (parent.Kind()) { case SyntaxKind.Argument: case SyntaxKind.LocalDeclarationStatement: case SyntaxKind.CastExpression: { return; } default: { if (parent is AssignmentExpressionSyntax assignment && assignment.Right == current) { return; } break; } } if (parent.IsKind(SyntaxKind.ExpressionStatement)) { break; } current = parent; } var curBlock = CurBlockOrNull; if (curBlock != null) { var statement = curBlock.Statements.FindLast(i => !(i is LuaBlankLinesStatement) && !(i is LuaCommentStatement)); if (statement != null) { statement.ForceSemicolon = true; } } } private LuaExpressionSyntax BuildMemberAccessTargetExpression(ExpressionSyntax targetExpression) { var expression = targetExpression.AcceptExpression(this); SyntaxKind kind = targetExpression.Kind(); if ((kind >= SyntaxKind.NumericLiteralExpression && kind <= SyntaxKind.NullLiteralExpression) || (expression is LuaLiteralExpressionSyntax)) { CheckPrevIsInvokeStatement(targetExpression); expression = expression.Parenthesized(); } return expression; } private LuaExpressionSyntax BuildMemberAccessExpression(ISymbol symbol, ExpressionSyntax node) { bool isExtensionMethod = symbol.Kind == SymbolKind.Method && ((IMethodSymbol)symbol).IsExtensionMethod; if (isExtensionMethod) { return node.AcceptExpression(this); } else { return BuildMemberAccessTargetExpression(node); } } private LuaExpressionSyntax CheckMemberAccessCodeTemplate(ISymbol symbol, MemberAccessExpressionSyntax node) { if (symbol.Kind == SymbolKind.Field) { IFieldSymbol fieldSymbol = (IFieldSymbol)symbol; if (fieldSymbol.ContainingType.IsTupleType) { int elementIndex = fieldSymbol.GetTupleElementIndex(); var targetExpression = node.Expression.AcceptExpression(this); return new LuaTableIndexAccessExpressionSyntax(targetExpression, elementIndex); } string codeTemplate = XmlMetaProvider.GetFieldCodeTemplate(fieldSymbol); if (codeTemplate != null) { return BuildCodeTemplateExpression(codeTemplate, node.Expression); } if (fieldSymbol.HasConstantValue) { if (!fieldSymbol.IsStringConstNotInline()) { return GetConstLiteralExpression(fieldSymbol); } } if (XmlMetaProvider.IsFieldForceProperty(fieldSymbol)) { var expression = node.Expression.AcceptExpression(this); var propertyIdentifierName = new LuaPropertyOrEventIdentifierNameSyntax(true, GetMemberName(symbol)); return new LuaPropertyAdapterExpressionSyntax(expression, propertyIdentifierName, !fieldSymbol.IsStatic); } } else if (symbol.Kind == SymbolKind.Property) { var propertySymbol = (IPropertySymbol)symbol; bool isGet = node.IsGetExpressionNode(); string codeTemplate = XmlMetaProvider.GetProertyCodeTemplate(propertySymbol, isGet); if (codeTemplate != null) { var result = BuildCodeTemplateExpression(codeTemplate, node.Expression); if (codeTemplate[0] == '#' && node.Parent.Parent.IsKind(SyntaxKind.InvocationExpression)) { result = result.Parenthesized(); } return result; } } return null; } private LuaExpressionSyntax InternalVisitMemberAccessExpression(ISymbol symbol, MemberAccessExpressionSyntax node) { var codeTemplateExpression = CheckMemberAccessCodeTemplate(symbol, node); if (codeTemplateExpression != null) { return codeTemplateExpression; } if (node.Expression.IsKind(SyntaxKind.ThisExpression)) { var nameExpression = node.Name.AcceptExpression(this); if (symbol.Kind == SymbolKind.Method) { if (IsDelegateExpression((IMethodSymbol)symbol, node, nameExpression, LuaIdentifierNameSyntax.This, out var delegateExpression)) { return delegateExpression; } } return nameExpression; } if (node.Expression.IsKind(SyntaxKind.BaseExpression)) { var baseExpression = node.Expression.AcceptExpression(this); var nameExpression = node.Name.AcceptExpression(this); if (symbol.Kind == SymbolKind.Property || symbol.Kind == SymbolKind.Event) { if (nameExpression is LuaPropertyAdapterExpressionSyntax propertyMethod) { if (baseExpression != LuaIdentifierNameSyntax.This) { propertyMethod.ArgumentList.AddArgument(LuaIdentifierNameSyntax.This); } propertyMethod.Update(baseExpression, false); return propertyMethod; } else { return baseExpression.MemberAccess(nameExpression); } } else { if (baseExpression == LuaIdentifierNameSyntax.This) { return baseExpression.MemberAccess(nameExpression, symbol.Kind == SymbolKind.Method); } else { return new LuaInternalMethodExpressionSyntax(baseExpression.MemberAccess(nameExpression)); } } } if (symbol.IsStatic && node.Expression.IsKind(SyntaxKind.IdentifierName) && CurTypeSymbol.IsContainsInternalSymbol(symbol)) { bool isOnlyName = false; switch (symbol.Kind) { case SymbolKind.Method: { isOnlyName = true; break; } case SymbolKind.Property: case SymbolKind.Event: { if (!generator_.IsPropertyFieldOrEventFiled(symbol)) { isOnlyName = true; } break; } case SymbolKind.Field: { if (symbol.IsPrivate()) { isOnlyName = true; } break; } } if (isOnlyName) { return node.Name.AcceptExpression(this); } } var name = node.Name.AcceptExpression(this); if (generator_.IsInlineSymbol(symbol)) { return name; } var expression = BuildMemberAccessExpression(symbol, node.Expression); if (symbol.Kind == SymbolKind.Property || symbol.Kind == SymbolKind.Event) { return BuildFieldOrPropertyMemberAccessExpression(expression, name, symbol.IsStatic); } if (symbol.Kind == SymbolKind.Method) { if (IsDelegateExpression((IMethodSymbol)symbol, node, name, expression, out var delegateExpression)) { return delegateExpression; } } return expression.MemberAccess(name, !symbol.IsStatic && symbol.Kind == SymbolKind.Method); } private bool IsDelegateExpression(IMethodSymbol symbol, MemberAccessExpressionSyntax node, LuaExpressionSyntax name, LuaExpressionSyntax expression, out LuaExpressionSyntax delegateExpression) { if (!node.Parent.IsKind(SyntaxKind.InvocationExpression)) { if (!IsInternalMember(symbol)) { name = expression.MemberAccess(name); } delegateExpression = BuildDelegateNameExpression(symbol, expression, name, node); return true; } else if (IsDelegateInvoke(symbol, node.Name)) { delegateExpression = expression; return true; } delegateExpression = null; return false; } private static bool IsDelegateInvoke(ISymbol symbol, SimpleNameSyntax name) { return symbol.ContainingType.IsDelegateType() && name.Identifier.ValueText == "Invoke"; } public override LuaSyntaxNode VisitMemberAccessExpression(MemberAccessExpressionSyntax node) { ISymbol symbol = semanticModel_.GetSymbolInfo(node).Symbol; if (symbol == null) { // dynamic var expressSymol = semanticModel_.GetSymbolInfo(node.Expression).Symbol; var expression = node.Expression.AcceptExpression(this); bool isObjectColon = node.Parent.IsKind(SyntaxKind.InvocationExpression) && (expressSymol == null || expressSymol.Kind != SymbolKind.NamedType); LuaIdentifierNameSyntax name = node.Name.Identifier.ValueText; return expression.MemberAccess(name, isObjectColon); } if (symbol.Kind == SymbolKind.NamedType) { var expressionSymbol = semanticModel_.GetSymbolInfo(node.Expression).Symbol; if (expressionSymbol.Kind == SymbolKind.Namespace || expressionSymbol.Kind == SymbolKind.NamedType) { return node.Name.Accept(this); } } return InternalVisitMemberAccessExpression(symbol, node); } private LuaExpressionSyntax BuildStaticFieldName(ISymbol symbol, bool isReadOnly, IdentifierNameSyntax node) { Contract.Assert(symbol.IsStatic); LuaIdentifierNameSyntax name = GetMemberName(symbol); bool isPrivate = symbol.IsPrivate(); if (isPrivate && generator_.IsForcePublicSymbol(symbol)) { isPrivate = false; } if (!isPrivate) { if (isReadOnly) { if (node.Parent.IsKind(SyntaxKind.SimpleAssignmentExpression)) { AssignmentExpressionSyntax assignmentExpression = (AssignmentExpressionSyntax)node.Parent; if (assignmentExpression.Left == node) { CurType.AddStaticReadOnlyAssignmentName(name); } } if (CheckUsingStaticNameSyntax(symbol, node, name, out var newExpression)) { return newExpression; } } else { if (IsInternalNode(node)) { if (CurFunctionOrNull is LuaConstructorAdapterExpressionSyntax ctor && ctor.IsStatic) { return LuaIdentifierNameSyntax.This.MemberAccess(name); } else { var typeName = GetTypeName(symbol.ContainingType); return typeName.MemberAccess(name); } } else { if (CheckUsingStaticNameSyntax(symbol, node, name, out var newExpression)) { return newExpression; } } } } else { if (!CurTypeSymbol.IsContainsInternalSymbol(symbol)) { if (symbol.IsPrivate()) { generator_.AddForcePublicSymbol(symbol); } var typeName = GetTypeName(symbol.ContainingType); return typeName.MemberAccess(name); } } return name; } private bool IsInternalNode(NameSyntax node) { var parentNode = node.Parent; switch (parentNode.Kind()) { case SyntaxKind.SimpleMemberAccessExpression: { MemberAccessExpressionSyntax parent = (MemberAccessExpressionSyntax)parentNode; if (parent.Expression.IsKind(SyntaxKind.ThisExpression)) { return true; } else if (parent.Expression == node) { return true; } return false; } case SyntaxKind.MemberBindingExpression: case SyntaxKind.NameColon: case SyntaxKind.NameEquals: { return false; } case SyntaxKind.SimpleAssignmentExpression: { AssignmentExpressionSyntax parent = (AssignmentExpressionSyntax)parentNode; if (parent.Right != node) { switch (parent.Parent.Kind()) { case SyntaxKind.ObjectInitializerExpression: case SyntaxKind.WithInitializerExpression: return false; } } break; } } return true; } private bool IsEventAddOrRemoveIdentifierName(IdentifierNameSyntax node) { SyntaxNode current = node; while (true) { var parent = current.Parent; if (parent == null) { break; } var kind = parent.Kind(); if (kind == SyntaxKind.AddAssignmentExpression || kind == SyntaxKind.SubtractAssignmentExpression) { var assignment = (AssignmentExpressionSyntax)parent; return assignment.Left == current; } else if (kind == SyntaxKind.SimpleMemberAccessExpression) { var memberAccessExpression = (MemberAccessExpressionSyntax)parent; if (memberAccessExpression.Name != current) { break; } } else { break; } current = parent; } return false; } private LuaExpressionSyntax VisitPropertyOrEventIdentifierName(IdentifierNameSyntax node, ISymbol symbol, bool isProperty, out bool isField) { bool isReadOnly; if (isProperty) { var propertySymbol = (IPropertySymbol)symbol; isField = IsPropertyField(propertySymbol); isReadOnly = propertySymbol.IsReadOnly; } else { var eventSymbol = (IEventSymbol)symbol; isField = IsEventFiled(eventSymbol); isReadOnly = false; if (!isField) { if (!IsEventAddOrRemoveIdentifierName(node)) { isField = true; } } } if (isField) { if (symbol.IsStatic) { return BuildStaticFieldName(symbol, isReadOnly, node); } else { LuaIdentifierNameSyntax fieldName = GetMemberName(symbol); if (IsInternalNode(node)) { return LuaIdentifierNameSyntax.This.MemberAccess(fieldName); } else { return fieldName; } } } else { if (isProperty) { var propertySymbol = (IPropertySymbol)symbol; if (IsWantInline(propertySymbol)) { if (InliningPropertyGetExpression(node, propertySymbol.GetMethod, out var inlineExpression)) { return inlineExpression; } } } var name = GetMemberName(symbol); var identifierName = new LuaPropertyOrEventIdentifierNameSyntax(isProperty, name); if (symbol.IsStatic) { var identifierExpression = new LuaPropertyAdapterExpressionSyntax(identifierName); if (CheckUsingStaticNameSyntax(symbol, node, identifierExpression, out var newExpression)) { if (symbol.IsPrivate()) { generator_.AddForcePublicSymbol(symbol); } return newExpression; } else if (symbol.IsPrivate() && !CurTypeSymbol.IsContainsInternalSymbol(symbol)) { generator_.AddForcePublicSymbol(symbol); var usingStaticType = GetTypeName(symbol.ContainingType); return usingStaticType.MemberAccess(identifierName); } return identifierExpression; } else { if (IsInternalMember(symbol)) { var propertyAdapter = new LuaPropertyAdapterExpressionSyntax(identifierName); propertyAdapter.ArgumentList.AddArgument(LuaIdentifierNameSyntax.This); return propertyAdapter; } else { if (IsInternalNode(node)) { return new LuaPropertyAdapterExpressionSyntax(LuaIdentifierNameSyntax.This, identifierName, true); } else { if (symbol.IsPrivate() && !CurTypeSymbol.IsContainsInternalSymbol(symbol)) { generator_.AddForcePublicSymbol(symbol); } return new LuaPropertyAdapterExpressionSyntax(identifierName); } } } } } private static bool IsParentDelegateName(NameSyntax node) { var kind = node.Parent.Kind(); switch (kind) { case SyntaxKind.SimpleMemberAccessExpression: case SyntaxKind.InvocationExpression: case SyntaxKind.MemberBindingExpression: return false; } return true; } private sealed class GenericPlaceholder { public ITypeSymbol Symbol { get; } private readonly int index_; public int TypeParameterIndex => index_ + 1; public bool IsTypeParameter => index_ != -1; public bool IsSwaped { get; private set; } public GenericPlaceholder(ITypeSymbol symbol, int index) { Symbol = symbol; index_ = index; } public GenericPlaceholder(ITypeSymbol symbol) : this(symbol, -1) { } public LuaExpressionSyntax Build(LuaSyntaxNodeTransform transform) { return IsTypeParameter ? TypeParameterIndex.ToString() : transform.GetTypeName(Symbol); } public static void Swap(List<GenericPlaceholder> placeholders, int x, int y) { var itemX = placeholders[x]; var itemY = placeholders[y]; placeholders[x] = itemY; placeholders[y] = itemX; itemX.IsSwaped = true; itemY.IsSwaped = true; } public static bool IsEnable(List<GenericPlaceholder> placeholders) { int index = 0; foreach (var placeholder in placeholders) { if (!placeholder.IsTypeParameter) { return true; } if (placeholder.index_ != index) { return true; } ++index; } return false; } } private sealed class TypeParameterPlaceholder { public ITypeSymbol Symbol; public int ParameterIndex; } private IMethodSymbol GetDelegateTargetMethodSymbol(CSharpSyntaxNode node) { var parent = node.Parent; switch (parent.Kind()) { case SyntaxKind.Argument: { var argument = (ArgumentSyntax)parent; var symbol = (IMethodSymbol)semanticModel_.GetSymbolInfo(argument.Parent.Parent).Symbol; var parameter = GetParameterSymbol(symbol.OriginalDefinition, argument); var type = (INamedTypeSymbol)parameter.Type; return type.DelegateInvokeMethod; } case SyntaxKind.EqualsValueClause: { var variableDeclaration = (VariableDeclarationSyntax)parent.Parent.Parent; var type = (INamedTypeSymbol)semanticModel_.GetTypeInfo(variableDeclaration.Type).Type; return type.DelegateInvokeMethod; } case SyntaxKind.SimpleAssignmentExpression: case SyntaxKind.AddAssignmentExpression: case SyntaxKind.SubtractAssignmentExpression: { var assignment = (AssignmentExpressionSyntax)parent; var type = (INamedTypeSymbol)semanticModel_.GetTypeInfo(assignment.Left).Type; return type.DelegateInvokeMethod; } case SyntaxKind.ReturnStatement: { var type = (INamedTypeSymbol)CurMethodInfoOrNull.Symbol.ReturnType; return type.DelegateInvokeMethod; } default: throw new InvalidProgramException(); } } private void CheckDelegateBind(IMethodSymbol symbol, CSharpSyntaxNode node, ref LuaExpressionSyntax nameExpression) { const int kReturnParameterIndex = int.MaxValue; if (symbol.IsGenericMethod) { var originalDefinition = symbol.OriginalDefinition; if (!originalDefinition.EQ(symbol)) { var targetMethodSymbol = GetDelegateTargetMethodSymbol(node); var targetTypeParameters = new List<TypeParameterPlaceholder>(); foreach (var typeArgument in targetMethodSymbol.ContainingType.TypeArguments) { if (typeArgument.TypeKind == TypeKind.TypeParameter) { int parameterIndex = targetMethodSymbol.Parameters.IndexOf(i => i.Type.IsTypeParameterExists(typeArgument)); if (parameterIndex == -1) { Contract.Assert(targetMethodSymbol.ReturnType != null && targetMethodSymbol.ReturnType.IsTypeParameterExists(typeArgument)); parameterIndex = kReturnParameterIndex; } targetTypeParameters.Add(new TypeParameterPlaceholder() { Symbol = typeArgument, ParameterIndex = parameterIndex, }); } } int j = 0; var originalTypeParameters = new List<TypeParameterPlaceholder>(); foreach (var originalTypeArgument in originalDefinition.TypeArguments) { Contract.Assert(originalTypeArgument.TypeKind == TypeKind.TypeParameter); int parameterIndex = originalDefinition.Parameters.IndexOf(i => i.Type.IsTypeParameterExists(originalTypeArgument)); if (parameterIndex != -1) { originalTypeParameters.Add(new TypeParameterPlaceholder() { Symbol = originalTypeArgument, ParameterIndex = parameterIndex, }); } else { if (originalDefinition.ReturnType != null && originalDefinition.ReturnType.IsTypeParameterExists(originalTypeArgument)) { originalTypeParameters.Add(new TypeParameterPlaceholder() { Symbol = originalTypeArgument, ParameterIndex = kReturnParameterIndex, }); } else { var typeArgument = symbol.TypeArguments[j]; Contract.Assert(typeArgument.TypeKind != TypeKind.TypeParameter); originalTypeParameters.Add(new TypeParameterPlaceholder() { Symbol = typeArgument, ParameterIndex = -1, }); } } ++j; } var placeholders = new List<GenericPlaceholder>(); foreach (var originalTypeParameter in originalTypeParameters) { int parameterIndex = originalTypeParameter.ParameterIndex; if (parameterIndex != -1) { int index = targetTypeParameters.FindIndex(i => i.ParameterIndex == parameterIndex); if (index != -1) { placeholders.Add(new GenericPlaceholder(originalTypeParameter.Symbol, index)); } else { ITypeSymbol parameterType; if (parameterIndex == kReturnParameterIndex) { Contract.Assert(targetMethodSymbol.ReturnType != null); parameterType = targetMethodSymbol.ReturnType; } else { var parameter = targetMethodSymbol.Parameters[parameterIndex]; parameterType = parameter.Type; } placeholders.Add(new GenericPlaceholder(parameterType)); } } else { placeholders.Add(new GenericPlaceholder(originalTypeParameter.Symbol)); } } if (GenericPlaceholder.IsEnable(placeholders)) { if (placeholders.TrueForAll(i => !i.IsTypeParameter)) { if (placeholders.Count <= 3) { string bindMethodName = LuaIdentifierNameSyntax.DelegateBind.ValueText + placeholders.Count; var invocationExpression = new LuaInvocationExpressionSyntax(bindMethodName, nameExpression); invocationExpression.AddArguments(placeholders.Select(i => i.Build(this))); nameExpression = invocationExpression; return; } } else if (symbol.Parameters.Length == 2) { if (placeholders.Count == 2) { if (placeholders[0].TypeParameterIndex == 2 && placeholders[1].TypeParameterIndex == 1) { string bindMethodName = LuaIdentifierNameSyntax.DelegateBind.ValueText + "2_1"; nameExpression = new LuaInvocationExpressionSyntax(bindMethodName, nameExpression); return; } } else if (placeholders.Count == 1) { if (placeholders.First().TypeParameterIndex == 2) { string bindMethodName = LuaIdentifierNameSyntax.DelegateBind.ValueText + "0_2"; nameExpression = new LuaInvocationExpressionSyntax(bindMethodName, nameExpression); return; } } } var invocation = new LuaInvocationExpressionSyntax(LuaIdentifierNameSyntax.DelegateBind, nameExpression, symbol.Parameters.Length.ToString()); invocation.AddArguments(placeholders.Select(i => i.Build(this))); nameExpression = invocation; } } } } private LuaExpressionSyntax BuildDelegateNameExpression(IMethodSymbol symbol, LuaExpressionSyntax target, LuaExpressionSyntax name, CSharpSyntaxNode node) { LuaExpressionSyntax nameExpression; if (symbol.IsStatic) { nameExpression = name; } else { nameExpression = new LuaInvocationExpressionSyntax(LuaIdentifierNameSyntax.DelegateMake, target, name); } CheckDelegateBind(symbol, node, ref nameExpression); return nameExpression; } private LuaExpressionSyntax BuildDelegateNameExpression(IMethodSymbol symbol, LuaExpressionSyntax name, CSharpSyntaxNode node) { return BuildDelegateNameExpression(symbol, LuaIdentifierNameSyntax.This, name, node); } private LuaExpressionSyntax GetMethodNameExpression(IMethodSymbol symbol, NameSyntax node) { LuaIdentifierNameSyntax methodName = GetMemberName(symbol); if (symbol.IsStatic) { if (CheckUsingStaticNameSyntax(symbol, node, methodName, out var outExpression)) { if (symbol.IsPrivate()) { generator_.AddForcePublicSymbol(symbol); } return outExpression; } if (IsInternalMember(symbol)) { if (IsParentDelegateName(node)) { return BuildDelegateNameExpression(symbol, methodName, node); } return new LuaInternalMethodExpressionSyntax(methodName); } if (CurTypeSymbol.IsContainsInternalSymbol(symbol) && IsMoreThanLocalVariables(symbol)) { return LuaIdentifierNameSyntax.MorenManyLocalVarTempTable.MemberAccess(methodName); } return methodName; } else { if (IsInternalMember(symbol)) { if (IsParentDelegateName(node)) { return BuildDelegateNameExpression(symbol, methodName, node); } return new LuaInternalMethodExpressionSyntax(methodName); } else { if (IsInternalNode(node)) { if (IsParentDelegateName(node)) { return BuildDelegateNameExpression(symbol, LuaIdentifierNameSyntax.This.MemberAccess(methodName), node); } return LuaIdentifierNameSyntax.This.MemberAccess(methodName, true); } else if (symbol.IsPrivate() && !CurTypeSymbol.IsContainsInternalSymbol(symbol)) { generator_.AddForcePublicSymbol(symbol); } } } return methodName; } private LuaExpressionSyntax GetFieldNameExpression(IFieldSymbol symbol, IdentifierNameSyntax node) { if (symbol.IsStatic) { if (symbol.HasConstantValue) { if (symbol.Type.SpecialType == SpecialType.System_String) { if (((string)symbol.ConstantValue).Length <= kStringConstInlineCount) { return GetConstLiteralExpression(symbol); } } else { return GetConstLiteralExpression(symbol); } } return BuildStaticFieldName(symbol, symbol.IsReadOnly, node); } else { if (IsInternalNode(node)) { if (symbol.IsProtobufNetSpecialField(out string name)) { return LuaIdentifierNameSyntax.This.MemberAccess(name); } return LuaIdentifierNameSyntax.This.MemberAccess(GetMemberName(symbol)); } else { return GetMemberName(symbol); } } } public override LuaSyntaxNode VisitIdentifierName(IdentifierNameSyntax node) { LuaIdentifierNameSyntax GetSampleName(ISymbol nodeSymbol) { LuaIdentifierNameSyntax nameIdentifier = nodeSymbol.Name; CheckLocalSymbolName(nodeSymbol, ref nameIdentifier); return nameIdentifier; } SymbolInfo symbolInfo = semanticModel_.GetSymbolInfo(node); ISymbol symbol = symbolInfo.Symbol; if (symbol == null) { // dynamic return (LuaIdentifierNameSyntax)node.Identifier.ValueText; } LuaExpressionSyntax identifier; switch (symbol.Kind) { case SymbolKind.Local: { var localSymbol = (ILocalSymbol)symbol; if (localSymbol.IsConst) { if (localSymbol.Type.SpecialType == SpecialType.System_String) { if (((string)localSymbol.ConstantValue).Length <= kStringConstInlineCount) { return GetConstLiteralExpression(localSymbol); } } else { return GetConstLiteralExpression(localSymbol); } } identifier = GetSampleName(symbol); CheckValueTypeClone(localSymbol.Type, node, ref identifier); break; } case SymbolKind.Parameter: { var parameterSymbol = (IParameterSymbol)symbol; identifier = GetSampleName(symbol); CheckValueTypeClone(parameterSymbol.Type, node, ref identifier); break; } case SymbolKind.RangeVariable: { identifier = GetRangeIdentifierName(node); break; } case SymbolKind.TypeParameter: case SymbolKind.Label: { identifier = symbol.Name; break; } case SymbolKind.NamedType: { identifier = GetTypeName(symbol); break; } case SymbolKind.Field: { var fieldSymbol = (IFieldSymbol)symbol; var codeTemplate = fieldSymbol.GetCodeTemplateFromAttribute(); if (codeTemplate != null) { identifier = BuildCodeTemplateExpression(codeTemplate, fieldSymbol.IsStatic ? null : LuaIdentifierNameSyntax.This); break; } identifier = GetFieldNameExpression(fieldSymbol, node); CheckValueTypeClone(fieldSymbol.Type, node, ref identifier); break; } case SymbolKind.Method: { var methodSymbol = (IMethodSymbol)symbol; if (methodSymbol.MethodKind == MethodKind.LocalFunction) { identifier = GetLocalMethodName(methodSymbol, node); } else { identifier = GetMethodNameExpression(methodSymbol, node); } break; } case SymbolKind.Property: { var propertyField = (IPropertySymbol)symbol; identifier = VisitPropertyOrEventIdentifierName(node, propertyField, true, out bool isField); if (isField) { CheckValueTypeClone(propertyField.Type, node, ref identifier, true); } break; } case SymbolKind.Event: { identifier = VisitPropertyOrEventIdentifierName(node, symbol, false, out _); break; } case SymbolKind.Discard: { identifier = LuaIdentifierNameSyntax.Placeholder; break; } default: { throw new NotSupportedException(); } } return identifier; } public override LuaSyntaxNode VisitQualifiedName(QualifiedNameSyntax node) { return node.Right.Accept(this); } private void FillInvocationArgument(List<LuaExpressionSyntax> arguments, ArgumentSyntax node, ImmutableArray<IParameterSymbol> parameters, List<RefOrOutArgument> refOrOutArguments) { var expression = node.Expression.AcceptExpression(this); Contract.Assert(expression != null); if (node.RefKindKeyword.IsKind(SyntaxKind.RefKeyword)) { refOrOutArguments.Add(new RefOrOutArgument(expression)); } else if (node.RefKindKeyword.IsKind(SyntaxKind.OutKeyword)) { refOrOutArguments.Add(new RefOrOutArgument(expression, node)); expression = LuaIdentifierNameSyntax.Nil; } else { CheckConversion(node.Expression, ref expression); } if (node.NameColon != null) { string name = node.NameColon.Name.Identifier.ValueText; int index = parameters.IndexOf(i => i.Name == name); if (index == -1) { throw new InvalidOperationException(); } arguments.AddAt(index, expression); } else { arguments.Add(expression); } } private List<LuaExpressionSyntax> BuildArgumentList(ISymbol symbol, ImmutableArray<IParameterSymbol> parameters, BaseArgumentListSyntax node, List<RefOrOutArgument> refOrOutArguments = null) { Contract.Assert(node != null); List<LuaExpressionSyntax> arguments = new List<LuaExpressionSyntax>(); foreach (var argument in node.Arguments) { FillInvocationArgument(arguments, argument, parameters, refOrOutArguments); } CheckInvocationDefaultArguments(symbol, parameters, arguments, node); return arguments; } private LuaArgumentListSyntax BuildArgumentList(SeparatedSyntaxList<ArgumentSyntax> arguments) { var argumentList = new LuaArgumentListSyntax(); foreach (var argument in arguments) { var newNode = argument.AcceptExpression(this); argumentList.Arguments.Add(newNode); } return argumentList; } public override LuaSyntaxNode VisitArgumentList(ArgumentListSyntax node) { return BuildArgumentList(node.Arguments); } public override LuaSyntaxNode VisitArgument(ArgumentSyntax node) { Contract.Assert(node.NameColon == null); return node.Expression.AcceptExpression(this); } private bool IsExtremelyZero(LiteralExpressionSyntax node, string value) { object v = semanticModel_.GetConstantValue(node).Value; var isFloatZero = (v is float f && f == 0) || (v is double d && d == 0); return isFloatZero && value.Length > 5; } private LuaExpressionSyntax InternalVisitLiteralExpression(LiteralExpressionSyntax node) { switch (node.Kind()) { case SyntaxKind.NumericLiteralExpression: { bool hasTransform = false; string value = node.Token.Text; value = value.Replace("_", ""); if (value.StartsWith("0b") || value.StartsWith("0B")) { value = node.Token.ValueText; hasTransform = true; } else { int len = value.Length; int removeCount = 0; switch (value[len - 1]) { case 'f': case 'F': case 'd': case 'D': { if (!value.StartsWith("0x") && !value.StartsWith("0X")) { if (IsExtremelyZero(node, value)) { value = LuaNumberLiteralExpressionSyntax.ZeroFloat.Text; hasTransform = true; } else { removeCount = 1; } } break; } case 'L': case 'l': { removeCount = 1; if (len > 2) { if (value[len - 2] == 'U' || value[len - 2] == 'u') { removeCount = 2; } } break; } case 'u': case 'U': case 'm': case 'M': { removeCount = 1; break; } } if (removeCount > 0) { value = value.Remove(len - removeCount); } } if (hasTransform) { return new LuaConstLiteralExpression(value, node.Token.Text); } else { return new LuaIdentifierLiteralExpressionSyntax(value); } } case SyntaxKind.StringLiteralExpression: { return BuildStringLiteralTokenExpression(node.Token); } case SyntaxKind.CharacterLiteralExpression: { return new LuaCharacterLiteralExpression((char)node.Token.Value); } case SyntaxKind.NullLiteralExpression: { return LuaIdentifierLiteralExpressionSyntax.Nil; } case SyntaxKind.DefaultLiteralExpression: { var type = semanticModel_.GetTypeInfo(node).Type; return GetDefaultValueExpression(type); } default: { return new LuaIdentifierLiteralExpressionSyntax(node.Token.ValueText); } } } public override LuaSyntaxNode VisitLiteralExpression(LiteralExpressionSyntax node) { return InternalVisitLiteralExpression(node); } public override LuaSyntaxNode VisitLocalDeclarationStatement(LocalDeclarationStatementSyntax node) { var declaration = node.Declaration.Accept<LuaVariableDeclarationSyntax>(this); if (node.UsingKeyword.IsKeyword()) { var block = CurBlock; if (block.UsingDeclarations == null) { block.UsingDeclarations = new List<int>(); } block.UsingDeclarations.Add(block.Statements.Count); } return new LuaLocalDeclarationStatementSyntax(declaration); } private bool IsValueTypeVariableDeclarationWithoutAssignment(VariableDeclaratorSyntax variable) { var body = FindParentMethodBody(variable); if (body != null) { int index = body.Statements.IndexOf((StatementSyntax)variable.Parent.Parent); foreach (var i in body.Statements.Skip(index + 1)) { if (i.IsKind(SyntaxKind.ExpressionStatement)) { var expressionStatement = (ExpressionStatementSyntax)i; if (expressionStatement.Expression.IsKind(SyntaxKind.SimpleAssignmentExpression)) { var assignment = (AssignmentExpressionSyntax)expressionStatement.Expression; if (assignment.Left.IsKind(SyntaxKind.IdentifierName)) { var identifierName = (IdentifierNameSyntax)assignment.Left; if (identifierName.Identifier.ValueText == variable.Identifier.ValueText) { return false; } } else if (assignment.Left.IsKind(SyntaxKind.SimpleMemberAccessExpression)) { var memberAccessExpression = (MemberAccessExpressionSyntax)assignment.Left; if (memberAccessExpression.Expression.IsKind(SyntaxKind.IdentifierName)) { var identifierName = (IdentifierNameSyntax)memberAccessExpression.Expression; if (identifierName.Identifier.ValueText == variable.Identifier.ValueText) { return true; } } } } } } } return false; } public override LuaSyntaxNode VisitVariableDeclaration(VariableDeclarationSyntax node) { ITypeSymbol typeSymbol = null; var variableListDeclaration = new LuaVariableListDeclarationSyntax(); foreach (var variable in node.Variables) { bool isRefIgnore = false; if (variable.Initializer != null && variable.Initializer.Value.IsKind(SyntaxKind.RefExpression)) { var value = (RefExpressionSyntax)variable.Initializer.Value; var refExpression = value.AcceptExpression(this); if (value.Expression.IsKind(SyntaxKind.InvocationExpression)) { var invocationExpression = (LuaInvocationExpressionSyntax)refExpression; AddRefInvocationVariableMapping((InvocationExpressionSyntax)value.Expression, invocationExpression, variable); } else { AddLocalVariableMapping(new LuaSymbolNameSyntax(refExpression), variable); isRefIgnore = true; } } if (!isRefIgnore) { bool isConst = false; if (node.Parent is LocalDeclarationStatementSyntax parent && parent.IsConst) { isConst = true; if (variable.Initializer.Value is LiteralExpressionSyntax value) { var token = value.Token; if (token.Value is string str) { if (str.Length > kStringConstInlineCount) { isConst = false; } } } } if (!isConst) { var variableDeclarator = variable.Accept<LuaVariableDeclaratorSyntax>(this); if (variableDeclarator.Initializer == null) { if (typeSymbol == null) { typeSymbol = semanticModel_.GetTypeInfo(node.Type).Type; } if (typeSymbol.IsCustomValueType() && IsValueTypeVariableDeclarationWithoutAssignment(variable)) { var typeExpression = GetTypeName(typeSymbol); variableDeclarator.Initializer = new LuaEqualsValueClauseSyntax(BuildDefaultValue(typeExpression)); } } variableListDeclaration.Variables.Add(variableDeclarator); } } } bool isMultiNil = variableListDeclaration.Variables.Count > 0 && variableListDeclaration.Variables.All(i => i.Initializer == null); if (isMultiNil) { LuaLocalVariablesSyntax declarationStatement = new LuaLocalVariablesSyntax(); foreach (var variable in variableListDeclaration.Variables) { declarationStatement.Variables.Add(variable.Identifier); } return declarationStatement; } else { return variableListDeclaration; } } public override LuaSyntaxNode VisitVariableDeclarator(VariableDeclaratorSyntax node) { LuaIdentifierNameSyntax identifier = node.Identifier.ValueText; CheckLocalVariableName(ref identifier, node); var variableDeclarator = new LuaVariableDeclaratorSyntax(identifier); if (node.Initializer != null) { variableDeclarator.Initializer = node.Initializer.Accept<LuaEqualsValueClauseSyntax>(this); } return variableDeclarator; } public override LuaSyntaxNode VisitEqualsValueClause(EqualsValueClauseSyntax node) { var expression = VisitExpression(node.Value); return new LuaEqualsValueClauseSyntax(expression); } public override LuaSyntaxNode VisitPredefinedType(PredefinedTypeSyntax node) { ISymbol symbol = semanticModel_.GetSymbolInfo(node).Symbol; return GetTypeShortName(symbol); } private void WriteStatementOrBlock(StatementSyntax statement, LuaBlockSyntax block) { if (statement.IsKind(SyntaxKind.Block)) { var blockNode = statement.Accept<LuaBlockSyntax>(this); block.Statements.AddRange(blockNode.Statements); } else { PushBlock(block); var statementNode = statement.Accept<LuaStatementSyntax>(this); block.Statements.Add(statementNode); PopBlock(); } } #region if else switch public override LuaSyntaxNode VisitIfStatement(IfStatementSyntax node) { var condition = VisitExpression(node.Condition); LuaIfStatementSyntax ifStatement = new LuaIfStatementSyntax(condition); WriteStatementOrBlock(node.Statement, ifStatement.Body); ifStatements_.Push(ifStatement); node.Else?.Accept(this); ifStatements_.Pop(); return ifStatement; } public override LuaSyntaxNode VisitElseClause(ElseClauseSyntax node) { if (node.Statement.IsKind(SyntaxKind.IfStatement)) { var ifStatement = (IfStatementSyntax)node.Statement; LuaBlockSyntax conditionBody = new LuaBlockSyntax(); PushBlock(conditionBody); var condition = VisitExpression(ifStatement.Condition); PopBlock(); if (conditionBody.Statements.Count == 0) { var elseIfStatement = new LuaElseIfStatementSyntax(condition); WriteStatementOrBlock(ifStatement.Statement, elseIfStatement.Body); ifStatements_.Peek().ElseIfStatements.Add(elseIfStatement); ifStatement.Else?.Accept(this); return elseIfStatement; } else { var elseClause = new LuaElseClauseSyntax(); elseClause.Body.Statements.AddRange(conditionBody.Statements); var elseIfStatement = new LuaIfStatementSyntax(condition); WriteStatementOrBlock(ifStatement.Statement, elseIfStatement.Body); elseClause.Body.AddStatement(elseIfStatement); ifStatements_.Peek().Else = elseClause; ifStatements_.Push(elseIfStatement); ifStatement.Else?.Accept(this); ifStatements_.Pop(); return elseClause; } } else { LuaElseClauseSyntax elseClause = new LuaElseClauseSyntax(); WriteStatementOrBlock(node.Statement, elseClause.Body); ifStatements_.Peek().Else = elseClause; return elseClause; } } public override LuaSyntaxNode VisitSwitchStatement(SwitchStatementSyntax node) { var temp = GetTempIdentifier(); var switchStatement = new LuaSwitchAdapterStatementSyntax(temp); switchs_.Push(switchStatement); var expression = node.Expression.AcceptExpression(this); switchStatement.Fill(expression, node.Sections.Select(i => i.Accept<LuaStatementSyntax>(this))); switchs_.Pop(); return switchStatement; } private void FillSwitchSectionStatements(LuaBlockSyntax block, SwitchSectionSyntax node) { if (node.Statements.Count == 1 && node.Statements.First().IsKind(SyntaxKind.Block)) { var luaBlock = node.Statements.First().Accept<LuaBlockSyntax>(this); block.Statements.AddRange(luaBlock.Statements); } else { PushBlock(block); var statements = VisitTriviaAndNode(node, node.Statements); block.AddStatements(statements); PopBlock(); } } public override LuaSyntaxNode VisitSwitchSection(SwitchSectionSyntax node) { bool isDefault = node.Labels.Any(i => i.Kind() == SyntaxKind.DefaultSwitchLabel); if (isDefault) { var block = new LuaBlockSyntax(); FillSwitchSectionStatements(block, node); return block; } else { var expressions = node.Labels.Select(i => i.AcceptExpression(this)); var condition = expressions.Aggregate((x, y) => x.Or(y)); var ifStatement = new LuaIfStatementSyntax(condition); FillSwitchSectionStatements(ifStatement.Body, node); return ifStatement; } } public override LuaSyntaxNode VisitCaseSwitchLabel(CaseSwitchLabelSyntax node) { var left = switchs_.Peek().Temp; var right = node.Value.AcceptExpression(this); return left.EqualsEquals(right); } private LuaExpressionSyntax BuildSwitchLabelWhenClause(LuaExpressionSyntax expression, WhenClauseSyntax whenClause) { if (whenClause != null) { var whenExpression = whenClause.AcceptExpression(this); return expression != null ? expression.And(whenExpression) : whenExpression; } else { return expression; } } private LuaExpressionSyntax BuildDeclarationPattern(DeclarationPatternSyntax declarationPattern, LuaIdentifierNameSyntax left, ExpressionSyntax expressionType, WhenClauseSyntax whenClause) { if (!declarationPattern.Designation.IsKind(SyntaxKind.DiscardDesignation)) { AddLocalVariableMapping(left, declarationPattern.Designation); } var isExpression = BuildIsPatternExpression(expressionType, declarationPattern.Type, left); if (isExpression == LuaIdentifierLiteralExpressionSyntax.True) { return whenClause != null ? whenClause.AcceptExpression(this) : LuaIdentifierLiteralExpressionSyntax.True; } else { return BuildSwitchLabelWhenClause(isExpression, whenClause); } } public override LuaSyntaxNode VisitCasePatternSwitchLabel(CasePatternSwitchLabelSyntax node) { var left = switchs_.Peek().Temp; switch (node.Pattern.Kind()) { case SyntaxKind.DeclarationPattern: { var switchStatement = (SwitchStatementSyntax)FindParent(node, SyntaxKind.SwitchStatement); var declarationPattern = (DeclarationPatternSyntax)node.Pattern; return BuildDeclarationPattern(declarationPattern, left, switchStatement.Expression, node.WhenClause); } case SyntaxKind.VarPattern: { var varPattern = (VarPatternSyntax)node.Pattern; AddLocalVariableMapping(left, varPattern.Designation); return BuildSwitchLabelWhenClause(null, node.WhenClause); } default: { var patternExpression = node.Pattern.AcceptExpression(this); var expression = left.EqualsEquals(patternExpression); return BuildSwitchLabelWhenClause(expression, node.WhenClause); } } } public override LuaSyntaxNode VisitWhenClause(WhenClauseSyntax node) { return node.Condition.AcceptExpression(this); } public override LuaSyntaxNode VisitConstantPattern(ConstantPatternSyntax node) { return node.Expression.AcceptExpression(this); } private void FillSwitchPatternSyntax(ref LuaIfStatementSyntax ifStatement, LuaExpressionSyntax condition, WhenClauseSyntax whenClause, LuaIdentifierNameSyntax assignmentLeft, ExpressionSyntax assignmentRight) { if (condition == null && whenClause == null) { condition = LuaIdentifierLiteralExpressionSyntax.True; } else { condition = BuildSwitchLabelWhenClause(condition, whenClause); } if (ifStatement == null) { ifStatement = new LuaIfStatementSyntax(condition); PushBlock(ifStatement.Body); var rightExpression = assignmentRight.AcceptExpression(this); PopBlock(); ifStatement.Body.AddStatement(assignmentLeft.Assignment(rightExpression)); } else { var elseIfStatement = new LuaElseIfStatementSyntax(condition); PushBlock(elseIfStatement.Body); var rightExpression = assignmentRight.AcceptExpression(this); PopBlock(); elseIfStatement.Body.AddStatement(assignmentLeft.Assignment(rightExpression)); ifStatement.ElseIfStatements.Add(elseIfStatement); } } private void CheckSwitchDeconstruct(ref LuaLocalVariablesSyntax deconstruct, LuaIdentifierNameSyntax identifier, ExpressionSyntax type, int count) { if (deconstruct == null) { var typeSymbol = semanticModel_.GetTypeInfo(type).Type; var deconstructInvocation = BuildDeconstructExpression(typeSymbol, identifier, type); deconstruct = new LuaLocalVariablesSyntax(); for (int i = 0; i < count; ++i) { deconstruct.Variables.Add(GetTempIdentifier()); } deconstruct.Initializer = new LuaEqualsValueClauseListSyntax(); deconstruct.Initializer.Values.Add(deconstructInvocation); } } public LuaExpressionSyntax BuildPropertyPatternNameExpression(LuaIdentifierNameSyntax governingIdentifier, IdentifierNameSyntax nameIdentifier) { var symbol = semanticModel_.GetSymbolInfo(nameIdentifier).Symbol; if (symbol.Kind == SymbolKind.Field) { var name = GetMemberName(symbol); return governingIdentifier.MemberAccess(name); } else { var propertySymbol = (IPropertySymbol)symbol; var codeTemplate = XmlMetaProvider.GetProertyCodeTemplate(propertySymbol, true); if (codeTemplate != null) { return InternalBuildCodeTemplateExpression(codeTemplate, null, null, null, governingIdentifier); } var name = nameIdentifier.AcceptExpression(this); return governingIdentifier.MemberAccess(name, name is LuaPropertyAdapterExpressionSyntax); } } private LuaExpressionSyntax BuildRecursivePatternExpression(RecursivePatternSyntax recursivePattern, LuaIdentifierNameSyntax governingIdentifier, LuaLocalVariablesSyntax deconstruct, ExpressionSyntax governingExpression) { var subpatterns = recursivePattern.PropertyPatternClause?.Subpatterns ?? recursivePattern.PositionalPatternClause.Subpatterns; var subpatternExpressions = new List<LuaExpressionSyntax>(); int subpatternIndex = 0; foreach (var subpattern in subpatterns) { var expression = subpattern.Pattern.AcceptExpression(this); if (subpattern.NameColon != null) { LuaExpressionSyntax left; if (governingIdentifier != null) { left = BuildPropertyPatternNameExpression(governingIdentifier, subpattern.NameColon.Name); } else { var fieldSymbol = (IFieldSymbol)semanticModel_.GetSymbolInfo(subpattern.NameColon.Name).Symbol; Contract.Assert(fieldSymbol.ContainingType.IsTupleType); int elementIndex = fieldSymbol.GetTupleElementIndex(); left = deconstruct.Variables[subpatternIndex]; } subpatternExpressions.Add(left.EqualsEquals(expression)); } else if (!subpattern.Pattern.IsKind(SyntaxKind.DiscardPattern)) { CheckSwitchDeconstruct(ref deconstruct, governingIdentifier, recursivePattern.Type ?? governingExpression, subpatterns.Count); var variable = deconstruct.Variables[subpatternIndex]; subpatternExpressions.Add(variable.EqualsEquals(expression)); } } ++subpatternIndex; LuaExpressionSyntax condition; if (subpatternExpressions.Count > 0) { condition = subpatternExpressions.Aggregate((x, y) => x.And(y)); } else { condition = governingIdentifier.NotEquals(LuaIdentifierNameSyntax.Nil); } if (recursivePattern.Type != null) { var isExpression = BuildIsPatternExpression(governingExpression, recursivePattern.Type, governingIdentifier); if (isExpression != LuaIdentifierLiteralExpressionSyntax.True) { condition = isExpression.And(condition); } } return condition; } public override LuaSyntaxNode VisitSwitchExpression(SwitchExpressionSyntax node) { const string kNewSwitchExpressionException = "System.SwitchExpressionException()"; var result = GetTempIdentifier(); CurBlock.AddStatement(new LuaLocalVariableDeclaratorSyntax(result)); LuaIdentifierNameSyntax governingIdentifier; LuaLocalVariablesSyntax deconstruct = null; var governingExpression = node.GoverningExpression.AcceptExpression(this); if (node.GoverningExpression.IsKind(SyntaxKind.TupleExpression)) { governingIdentifier = null; var invocation = (LuaInvocationExpressionSyntax)governingExpression; deconstruct = new LuaLocalVariablesSyntax(); for (int i = 0; i < invocation.ArgumentList.Arguments.Count; ++i) { deconstruct.Variables.Add(GetTempIdentifier()); } deconstruct.Initializer = new LuaEqualsValueClauseListSyntax(); deconstruct.Initializer.Values.AddRange(invocation.ArgumentList.Arguments); } else { governingIdentifier = GetTempIdentifier(); CurBlock.AddStatement(new LuaLocalVariableDeclaratorSyntax(governingIdentifier, governingExpression)); } LuaIfStatementSyntax ifStatement = null; foreach (var arm in node.Arms) { switch (arm.Pattern.Kind()) { case SyntaxKind.ConstantPattern: { var patternExpression = arm.Pattern.AcceptExpression(this); var condition = governingIdentifier.EqualsEquals(patternExpression); FillSwitchPatternSyntax(ref ifStatement, condition, arm.WhenClause, result, arm.Expression); break; } case SyntaxKind.RecursivePattern: { var recursivePattern = (RecursivePatternSyntax)arm.Pattern; if (recursivePattern.Designation != null) { AddLocalVariableMapping(governingIdentifier, recursivePattern.Designation); } var condition = BuildRecursivePatternExpression(recursivePattern, governingIdentifier, deconstruct, node.GoverningExpression); FillSwitchPatternSyntax(ref ifStatement, condition, arm.WhenClause, result, arm.Expression); break; } case SyntaxKind.DeclarationPattern: { var declarationPattern = (DeclarationPatternSyntax)arm.Pattern; var condition = BuildDeclarationPattern(declarationPattern, governingIdentifier, node.GoverningExpression, arm.WhenClause); FillSwitchPatternSyntax(ref ifStatement, condition, null, result, arm.Expression); break; } case SyntaxKind.VarPattern: { var varPatternSyntax = (VarPatternSyntax)arm.Pattern; var parenthesizedVariable = (ParenthesizedVariableDesignationSyntax)varPatternSyntax.Designation; int variableIndex = 0; foreach (var variable in parenthesizedVariable.Variables) { if (!variable.IsKind(SyntaxKind.DiscardDesignation)) { CheckSwitchDeconstruct(ref deconstruct, governingIdentifier, node.GoverningExpression, parenthesizedVariable.Variables.Count); var variableName = deconstruct.Variables[variableIndex]; AddLocalVariableMapping(variableName, variable); } ++variableIndex; } FillSwitchPatternSyntax(ref ifStatement, null, arm.WhenClause, result, arm.Expression); break; } case SyntaxKind.DiscardPattern: { var elseClause = new LuaElseClauseSyntax(); PushBlock(elseClause.Body); var rightExpression = arm.Expression.AcceptExpression(this); PopBlock(); elseClause.Body.AddStatement(result.Assignment(rightExpression)); ifStatement.Else = elseClause; break; } default: { throw new NotImplementedException(); } } } if (ifStatement.Else == null) { var elseClause = new LuaElseClauseSyntax(); elseClause.Body.AddStatement(LuaIdentifierNameSyntax.Throw.Invocation(kNewSwitchExpressionException)); ifStatement.Else = elseClause; } if (deconstruct != null) { CurBlock.AddStatement(deconstruct); } CurBlock.AddStatement(ifStatement); return result; } #endregion private bool IsParnetTryStatement(SyntaxNode node) { bool isTry = false; FindParent(node, i => { var kind = i.Kind(); switch (kind) { case SyntaxKind.WhileStatement: case SyntaxKind.DoStatement: case SyntaxKind.ForStatement: case SyntaxKind.ForEachStatement: case SyntaxKind.SwitchStatement: return true; case SyntaxKind.TryStatement: case SyntaxKind.UsingStatement: isTry = true; return true; } return false; }); return isTry; } private bool CheckBreakLastBlockStatement(BreakStatementSyntax node) { if (IsLuaClassic) { switch (node.Parent.Kind()) { case SyntaxKind.Block: { var block = (BlockSyntax)node.Parent; return block.Statements.Last() != node; } case SyntaxKind.SwitchSection: { var switchSection = (SwitchSectionSyntax)node.Parent; return switchSection.Statements.Last() != node; } } } return false; } public override LuaSyntaxNode VisitBreakStatement(BreakStatementSyntax node) { if (IsParnetTryStatement(node)) { var check = (LuaCheckLoopControlExpressionSyntax)CurFunction; check.HasBreak = true; return new LuaReturnStatementSyntax(LuaIdentifierLiteralExpressionSyntax.False); } if (CheckBreakLastBlockStatement(node)) { var blockStatement = new LuaBlockStatementSyntax(); blockStatement.Statements.Add(LuaBreakStatementSyntax.Instance); return blockStatement; } return LuaBreakStatementSyntax.Instance; } private LuaExpressionSyntax BuildEnumToStringExpression(ITypeSymbol typeInfo, bool isNullable, LuaExpressionSyntax original, ExpressionSyntax node) { if (original is LuaLiteralExpressionSyntax) { var symbol = semanticModel_.GetSymbolInfo(node).Symbol; return new LuaConstLiteralExpression(new LuaStringLiteralExpressionSyntax(symbol.Name), typeInfo.ToString()); } AddExportEnum(typeInfo); var typeName = GetTypeShortName(typeInfo); if (IsPreventDebug || isNullable) { return LuaIdentifierNameSyntax.System.MemberAccess(LuaIdentifierNameSyntax.EnumToString).Invocation(original, typeName); } else { return original.MemberAccess(LuaIdentifierNameSyntax.EnumToString, true).Invocation(typeName); } } private LuaExpressionSyntax WrapStringConcatExpression(ExpressionSyntax expression) { ITypeSymbol typeInfo = semanticModel_.GetTypeInfo(expression).Type; var original = expression.AcceptExpression(this); if (typeInfo.IsStringType()) { if (IsPreventDebug && !expression.IsKind(SyntaxKind.AddExpression) && !expression.IsKind(SyntaxKind.StringLiteralExpression)) { return new LuaInvocationExpressionSyntax(LuaIdentifierNameSyntax.SystemToString, original); } return original; } else if (typeInfo.SpecialType == SpecialType.System_Char) { var constValue = semanticModel_.GetConstantValue(expression); if (constValue.HasValue) { string text = SyntaxFactory.Literal((char)constValue.Value).Text; return new LuaIdentifierLiteralExpressionSyntax(text); } else { return new LuaInvocationExpressionSyntax(LuaIdentifierNameSyntax.StringChar, original); } } else if (typeInfo.SpecialType >= SpecialType.System_Boolean && typeInfo.SpecialType <= SpecialType.System_Double) { if (IsPreventDebug && typeInfo.SpecialType == SpecialType.System_Boolean) { return new LuaInvocationExpressionSyntax(LuaIdentifierNameSyntax.SystemToString, original); } return original; } else if (typeInfo.IsEnumType(out var enumTypeSymbol, out bool isNullable)) { return BuildEnumToStringExpression(enumTypeSymbol, isNullable, original, expression); } else if (typeInfo.IsValueType) { return original.MemberAccess(LuaIdentifierNameSyntax.ToStr, true).Invocation(); } else { return LuaIdentifierNameSyntax.SystemToString.Invocation(original); } } private LuaExpressionSyntax BuildStringConcatExpression(BinaryExpressionSyntax node) { return BuildStringConcatExpression(node.Left, node.Right); } private LuaExpressionSyntax BuildStringConcatExpression(ExpressionSyntax leftNode, ExpressionSyntax rightNode) { var left = WrapStringConcatExpression(leftNode); var right = WrapStringConcatExpression(rightNode); return left.Binary(LuaSyntaxNode.Tokens.Concatenation, right); } private LuaExpressionSyntax BuildBinaryInvokeExpression(BinaryExpressionSyntax node, LuaExpressionSyntax name) { var left = node.Left.AcceptExpression(this); var right = node.Right.AcceptExpression(this); return new LuaInvocationExpressionSyntax(name, left, right); } private LuaBinaryExpressionSyntax BuildBinaryExpression(BinaryExpressionSyntax node, string operatorToken) { var left = VisitExpression(node.Left); var right = VisitExpression(node.Right); return left.Binary(operatorToken, right); } private bool IsNullableType(BinaryExpressionSyntax node, out bool isLeftNullable, out bool isRightNullable) { var leftType = semanticModel_.GetTypeInfo(node.Left).Type; var rightType = semanticModel_.GetTypeInfo(node.Right).Type; isLeftNullable = leftType != null && leftType.IsNullableType(); isRightNullable = rightType != null && rightType.IsNullableType(); return isLeftNullable || isRightNullable; } private bool IsNullableType(BinaryExpressionSyntax node) => IsNullableType(node, out _, out _); private LuaExpressionSyntax BuildBoolXorOfNullExpression(BinaryExpressionSyntax node, bool isLeftNullable, bool isRightNullable) { var left = VisitExpression(node.Left); var right = VisitExpression(node.Right); if (left.IsNil() || right.IsNil()) { return new LuaConstLiteralExpression(LuaIdentifierLiteralExpressionSyntax.Nil, node.ToString()); } var temp = GetTempIdentifier(); CurBlock.AddStatement(new LuaLocalVariableDeclaratorSyntax(temp)); var identifiers = BuildNumberNullableIdentifiers(ref left, ref right, isLeftNullable, isRightNullable); LuaExpressionSyntax condition; if (identifiers.Count == 1) { condition = identifiers.First().NotEquals(LuaIdentifierNameSyntax.Nil); } else { condition = left.NotEquals(LuaIdentifierNameSyntax.Nil).And(right.NotEquals(LuaIdentifierNameSyntax.Nil)); } var ifStatement = new LuaIfStatementSyntax(condition); ifStatement.Body.AddStatement(temp.Assignment(left.NotEquals(right))); CurBlock.AddStatement(ifStatement); return temp; } private LuaExpressionSyntax BuildLeftNullableBoolLogicExpression(BinaryExpressionSyntax node, string boolOperatorToken) { var left = VisitExpression(node.Left); var right = VisitExpression(node.Right); var temp = GetTempIdentifier(); CurBlock.AddStatement(new LuaLocalVariableDeclaratorSyntax(temp)); var identifier = BuildNullableExpressionIdentifier(left, new List<LuaExpressionSyntax>()); var ifStatement = new LuaIfStatementSyntax(identifier.EqualsEquals(LuaIdentifierNameSyntax.Nil)); ifStatement.Body.AddStatement(temp.Assignment(right.Binary(boolOperatorToken, identifier))); ifStatement.Else = new LuaElseClauseSyntax(); ifStatement.Else.Body.AddStatement(temp.Assignment(identifier.Binary(boolOperatorToken, right))); CurBlock.AddStatement(ifStatement); return temp; } private LuaExpressionSyntax BuildBitExpression(BinaryExpressionSyntax node, string boolOperatorToken, LuaIdentifierNameSyntax bitMethodName) { if (semanticModel_.GetSymbolInfo(node).Symbol is IMethodSymbol methodSymbol) { var containingType = methodSymbol.ContainingType; if (containingType != null) { if (containingType.IsBoolType(false)) { switch (node.Kind()) { case SyntaxKind.ExclusiveOrExpression: { if (IsNullableType(node, out bool isLeftNullable, out bool isRightNullable)) { return BuildBoolXorOfNullExpression(node, isLeftNullable, isRightNullable); } break; } case SyntaxKind.BitwiseOrExpression: case SyntaxKind.BitwiseAndExpression: { if (IsNullableType(node, out bool isLeftNullable, out _) && isLeftNullable) { return BuildLeftNullableBoolLogicExpression(node, boolOperatorToken); } break; } } return BuildBinaryExpression(node, boolOperatorToken); } if (containingType.IsIntegerType(false) || containingType.TypeKind == TypeKind.Enum) { if (IsLuaClassic) { if (IsNullableBinaryExpression(node, null, out var result, bitMethodName)) { return result; } return BuildBinaryInvokeExpression(node, bitMethodName); } else if (IsPreventDebug && IsNullableBinaryExpression(node, null, out var result, bitMethodName)) { return result; } } } } return null; } private LuaExpressionSyntax BuildLogicOrBinaryExpression(BinaryExpressionSyntax node) { var left = VisitExpression(node.Left); LuaBlockSyntax rightBody = new LuaBlockSyntax(); PushBlock(rightBody); var right = VisitExpression(node.Right); if (rightBody.Statements.Count == 0) { PopBlock(); return left.Or(right); } else { var temp = GetTempIdentifier(); PopBlock(); CurBlock.Statements.Add(new LuaLocalVariableDeclaratorSyntax(temp)); LuaIfStatementSyntax leftIfStatement = new LuaIfStatementSyntax(left); CurBlock.Statements.Add(leftIfStatement); leftIfStatement.Body.AddStatement(temp.Assignment(LuaIdentifierNameSyntax.True)); leftIfStatement.Else = new LuaElseClauseSyntax(); leftIfStatement.Else.Body.Statements.AddRange(rightBody.Statements); LuaIfStatementSyntax rightIfStatement = new LuaIfStatementSyntax(right); leftIfStatement.Else.Body.AddStatement(rightIfStatement); rightIfStatement.Body.AddStatement(temp.Assignment(LuaIdentifierNameSyntax.True)); return temp; } } private LuaExpressionSyntax BuildLogicAndBinaryExpression(BinaryExpressionSyntax node) { var left = VisitExpression(node.Left); LuaBlockSyntax rightBody = new LuaBlockSyntax(); PushBlock(rightBody); var right = VisitExpression(node.Right); if (rightBody.Statements.Count == 0) { PopBlock(); return left.And(right); } else { var temp = GetTempIdentifier(); PopBlock(); CurBlock.Statements.Add(new LuaLocalVariableDeclaratorSyntax(temp)); LuaIfStatementSyntax leftIfStatement = new LuaIfStatementSyntax(left); CurBlock.Statements.Add(leftIfStatement); leftIfStatement.Body.Statements.AddRange(rightBody.Statements); LuaIfStatementSyntax rightIfStatement = new LuaIfStatementSyntax(right); leftIfStatement.Body.AddStatement(rightIfStatement); rightIfStatement.Body.AddStatement(temp.Assignment(LuaIdentifierNameSyntax.True)); return temp; } } private bool IsNullableBinaryExpression(BinaryExpressionSyntax node, string operatorToken, out LuaExpressionSyntax result, LuaIdentifierNameSyntax method = null) { if (IsNullableType(node, out bool isLeftNullable, out bool isRightNullable)) { var left = node.Left.AcceptExpression(this); var right = node.Right.AcceptExpression(this); result = BuildNumberNullableExpression(left, right, operatorToken, isLeftNullable, isRightNullable, method); return true; } result = null; return false; } private bool IsNumberNullableBinaryExpression(INamedTypeSymbol containingType, BinaryExpressionSyntax node, string operatorToken, out LuaExpressionSyntax result, LuaIdentifierNameSyntax method = null) { if (containingType.IsNumberType(false)) { if (IsNullableBinaryExpression(node, operatorToken, out result, method)) { return true; } } result = null; return false; } private LuaExpressionSyntax BuildNumberBinaryExpression(BinaryExpressionSyntax node, SyntaxKind kind) { if (semanticModel_.GetSymbolInfo(node).Symbol is IMethodSymbol methodSymbol) { var containingType = methodSymbol.ContainingType; if (containingType != null) { if (kind == SyntaxKind.AddExpression && containingType.IsStringType()) { return BuildStringConcatExpression(node); } if (IsPreventDebug) { switch (kind) { case SyntaxKind.AddExpression: case SyntaxKind.SubtractExpression: { bool isPlus = node.IsKind(SyntaxKind.AddExpression); if (containingType.IsDelegateType()) { return BuildBinaryInvokeExpression(node, isPlus ? LuaIdentifierNameSyntax.DelegateCombine : LuaIdentifierNameSyntax.DelegateRemove); } if (IsNumberNullableBinaryExpression(containingType, node, isPlus ? LuaSyntaxNode.Tokens.Plus : LuaSyntaxNode.Tokens.Sub, out var result)) { return result; } break; } case SyntaxKind.MultiplyExpression: { if (IsNumberNullableBinaryExpression(containingType, node, LuaSyntaxNode.Tokens.Multiply, out var result)) { return result; } break; } case SyntaxKind.LessThanExpression: case SyntaxKind.LessThanOrEqualExpression: case SyntaxKind.GreaterThanExpression: case SyntaxKind.GreaterThanOrEqualExpression: { var operatorToken = GetOperatorToken(node.OperatorToken); if (IsNumberNullableBinaryExpression(containingType, node, operatorToken, out var result)) { return result.Or(LuaIdentifierNameSyntax.False); } break; } } } switch (kind) { case SyntaxKind.DivideExpression: { if (IsPreventDebug && containingType.IsDoubleOrFloatType(false)) { if (IsNullableBinaryExpression(node, LuaSyntaxNode.Tokens.Div, out var result)) { return result; } } if (containingType.IsIntegerType(false)) { if (IsNullableType(node)) { if (IsLuaClassic || IsPreventDebug) { bool success = IsNullableBinaryExpression(node, null, out var result, LuaIdentifierNameSyntax.IntegerDiv); Contract.Assert(success); return result; } } return BuildBinaryInvokeExpression(node, LuaIdentifierNameSyntax.IntegerDiv); } break; } case SyntaxKind.ModuloExpression: { if (containingType.IsNumberType(false)) { if (IsLuaClassic) { var method = containingType.IsIntegerType(false) ? LuaIdentifierNameSyntax.Mod : LuaIdentifierNameSyntax.ModFloat; if (IsNullableBinaryExpression(node, null, out var result, method)) { return result; } return BuildBinaryInvokeExpression(node, method); } else { if (IsPreventDebug && IsNullableBinaryExpression(node, null, out var result, LuaIdentifierNameSyntax.Mod)) { return result; } return BuildBinaryInvokeExpression(node, LuaIdentifierNameSyntax.Mod); } } break; } case SyntaxKind.LeftShiftExpression: case SyntaxKind.RightShiftExpression: { if (containingType.IsIntegerType(false)) { bool isLeftShift = kind == SyntaxKind.LeftShiftExpression; string operatorToken = isLeftShift ? LuaSyntaxNode.Tokens.ShiftLeft : LuaSyntaxNode.Tokens.ShiftRight; if (IsLuaClassic) { var method = isLeftShift ? LuaIdentifierNameSyntax.ShiftLeft : LuaIdentifierNameSyntax.ShiftRight; if (IsNullableBinaryExpression(node, operatorToken, out var result, method)) { return result; } return BuildBinaryInvokeExpression(node, method); } else if (IsPreventDebug && IsNullableBinaryExpression(node, operatorToken, out var result)) { return result; } } break; } } } } return null; } public override LuaSyntaxNode VisitBinaryExpression(BinaryExpressionSyntax node) { LuaExpressionSyntax resultExpression = GetConstExpression(node); if (resultExpression != null) { return resultExpression; } var kind = node.Kind(); switch (kind) { case SyntaxKind.AddExpression: case SyntaxKind.SubtractExpression: case SyntaxKind.MultiplyExpression: case SyntaxKind.DivideExpression: case SyntaxKind.ModuloExpression: case SyntaxKind.LeftShiftExpression: case SyntaxKind.RightShiftExpression: case SyntaxKind.LessThanExpression: case SyntaxKind.LessThanOrEqualExpression: case SyntaxKind.GreaterThanExpression: case SyntaxKind.GreaterThanOrEqualExpression: resultExpression = BuildNumberBinaryExpression(node, kind); break; case SyntaxKind.BitwiseOrExpression: { resultExpression = BuildBitExpression(node, LuaSyntaxNode.Tokens.Or, LuaIdentifierNameSyntax.BitOr); break; } case SyntaxKind.BitwiseAndExpression: { resultExpression = BuildBitExpression(node, LuaSyntaxNode.Tokens.And, LuaIdentifierNameSyntax.BitAnd); break; } case SyntaxKind.ExclusiveOrExpression: { resultExpression = BuildBitExpression(node, LuaSyntaxNode.Tokens.NotEquals, LuaIdentifierNameSyntax.BitXor); break; } case SyntaxKind.IsExpression: { var rightType = semanticModel_.GetTypeInfo(node.Right).Type; if (rightType.IsNullableType(out var nullElementType)) { var left = node.Left.AcceptExpression(this); var right = GetTypeName(nullElementType); return new LuaInvocationExpressionSyntax(LuaIdentifierNameSyntax.Is, left, right); } var leftType = semanticModel_.GetTypeInfo(node.Left).Type; if (leftType.Is(rightType)) { if (leftType.IsValueType) { return LuaIdentifierLiteralExpressionSyntax.True; } else { return node.Left.AcceptExpression(this).NotEquals(LuaIdentifierNameSyntax.Nil); } } var constValue = semanticModel_.GetConstantValue(node.Right); if (constValue.HasValue) { var leftExpression = node.Left.AcceptExpression(this); return BuildIsConstantExpression(leftExpression, node.Right, constValue); } return BuildBinaryInvokeExpression(node, LuaIdentifierNameSyntax.Is); } case SyntaxKind.AsExpression: { if (node.Left.IsKind(SyntaxKind.NullLiteralExpression)) { return LuaIdentifierLiteralExpressionSyntax.Nil; } var leftType = semanticModel_.GetTypeInfo(node.Left).Type; var rightType = semanticModel_.GetTypeInfo(node.Right).Type; if (leftType.Is(rightType)) { return node.Left.Accept(this); } var left = node.Left.AcceptExpression(this); var right = node.Right.AcceptExpression(this); if (rightType.IsNullableType()) { right = ((LuaInvocationExpressionSyntax)right).Arguments.First(); } return new LuaInvocationExpressionSyntax(LuaIdentifierNameSyntax.As, left, right); } case SyntaxKind.LogicalOrExpression: { return BuildLogicOrBinaryExpression(node); } case SyntaxKind.LogicalAndExpression: { return BuildLogicAndBinaryExpression(node); } case SyntaxKind.CoalesceExpression: { var left = node.Left.AcceptExpression(this); var temp = GetTempIdentifier(); var block = new LuaBlockSyntax(); PushBlock(block); var right = node.Right.AcceptExpression(this); PopBlock(); if (block.Statements.Count == 0) { var typeSymbol = semanticModel_.GetTypeInfo(node.Left).Type; bool isBool = typeSymbol != null && typeSymbol.IsBoolType(); if (!isBool) { AddReleaseTempIdentifier(temp); return left.Binary(GetOperatorToken(node.OperatorToken), right); } } CurBlock.AddStatement(new LuaLocalVariableDeclaratorSyntax(temp, left)); var ifStatement = new LuaIfStatementSyntax(temp.EqualsEquals(LuaIdentifierNameSyntax.Nil)); ifStatement.Body.AddStatements(block.Statements); ifStatement.Body.AddStatement(temp.Assignment(right)); CurBlock.AddStatement(ifStatement); return temp; } } if (resultExpression != null) { return resultExpression; } if (IsUserDefinedOperator(node, out var methodSymbol)) { if (IsNullableTypeUserDefinedOperator(node, methodSymbol, out var result)) { return result; } return GetUserDefinedOperatorExpression(methodSymbol, node.Left, node.Right); } string operatorToken = GetOperatorToken(node.OperatorToken); return BuildBinaryExpression(node, operatorToken); } private bool IsNullableTypeUserDefinedOperator(BinaryExpressionSyntax node, IMethodSymbol methodSymbol, out LuaExpressionSyntax result) { if (IsNullableType(node, out bool isLeftNullable, out bool isRightNullable)) { var arguments = new List<Func<LuaExpressionSyntax>>(); var identifiers = new List<LuaExpressionSyntax>(); if (isLeftNullable) { if (isRightNullable) { arguments.Add(() => BuildNullableExpressionIdentifier(node.Left, identifiers)); arguments.Add(() => BuildNullableExpressionIdentifier(node.Right, identifiers)); } else { arguments.Add(() => BuildNullableExpressionIdentifier(node.Left, identifiers)); arguments.Add(() => VisitExpression(node.Right)); } } else { arguments.Add(() => VisitExpression(node.Left)); arguments.Add(() => BuildNullableExpressionIdentifier(node.Right, identifiers)); } var operatorExpression = GetUserDefinedOperatorExpression(methodSymbol, arguments); switch (node.Kind()) { case SyntaxKind.EqualsExpression: case SyntaxKind.NotEqualsExpression: { var prevIdentifiers = identifiers.ToList(); TransformIdentifiersForCompareExpression(identifiers); var temp = GetTempIdentifier(); CurBlock.AddStatement(new LuaLocalVariableDeclaratorSyntax(temp)); var ifStatement = new LuaIfStatementSyntax(identifiers.Aggregate((x, y) => x.And(y))); ifStatement.Body.AddStatement(temp.Assignment(operatorExpression)); ifStatement.Else = new LuaElseClauseSyntax(); LuaExpressionSyntax right; if (node.IsKind(SyntaxKind.EqualsExpression)) { if (identifiers.Count == 1) { right = LuaIdentifierLiteralExpressionSyntax.False; } else { Contract.Assert(identifiers.Count == 2); right = prevIdentifiers.First().EqualsEquals(prevIdentifiers.Last()); } } else { if (identifiers.Count == 1) { right = LuaIdentifierLiteralExpressionSyntax.True; } else { Contract.Assert(identifiers.Count == 2); right = prevIdentifiers.First().NotEquals(prevIdentifiers.Last()); } } ifStatement.Else.Body.AddStatement(temp.Assignment(right)); CurBlock.AddStatement(ifStatement); result = temp; return true; } case SyntaxKind.LessThanExpression: case SyntaxKind.LessThanOrEqualExpression: case SyntaxKind.GreaterThanExpression: case SyntaxKind.GreaterThanOrEqualExpression: { TransformIdentifiersForCompareExpression(identifiers); break; } } result = identifiers.Aggregate((x, y) => x.And(y)).And(operatorExpression); return true; } result = null; return false; } private LuaExpressionSyntax BuildNullableExpressionIdentifier(ExpressionSyntax node, List<LuaExpressionSyntax> identifiers) { var expression = node.AcceptExpression(this); return BuildNullableExpressionIdentifier(expression, identifiers); } private LuaIdentifierNameSyntax BuildNullableExpressionIdentifier(LuaExpressionSyntax expression, List<LuaExpressionSyntax> identifiers) { if (expression is LuaIdentifierNameSyntax identifierName) { identifiers.Add(identifierName); return identifierName; } else { var temp = GetTempIdentifier(); CurBlock.AddStatement(new LuaLocalVariableDeclaratorSyntax(temp, expression)); identifiers.Add(temp); return temp; } } private bool IsSingleLineUnary(ExpressionSyntax node) { switch (node.Parent.Kind()) { case SyntaxKind.ExpressionStatement: case SyntaxKind.ForStatement: { return true; } case SyntaxKind.SimpleLambdaExpression: case SyntaxKind.ParenthesizedLambdaExpression: { var method = CurMethodInfoOrNull.Symbol; if (method.ReturnsVoid) { return true; } break; } } return false; } private void ChecktIncrementExpression(ExpressionSyntax operand, ref LuaExpressionSyntax expression, bool isAddOrAssignment) { var symbol = semanticModel_.GetTypeInfo(operand).Type; if (!symbol.IsNumberType()) { var op_Implicits = symbol.GetMembers("op_Implicit").OfType<IMethodSymbol>(); var methodSymbol = op_Implicits.FirstOrDefault(i => isAddOrAssignment ? i.ReturnType.IsIntegerType() : i.ReturnType.EQ(symbol)); if (methodSymbol != null) { expression = BuildConversionExpression(methodSymbol, expression); } } } private LuaSyntaxNode BuildPrefixUnaryExpression(bool isSingleLine, string operatorToken, LuaExpressionSyntax operand, PrefixUnaryExpressionSyntax node, bool isLocalVar = false) { var left = operand; ChecktIncrementExpression(node.Operand, ref left, true); LuaExpressionSyntax binary = left.Binary(operatorToken, LuaIdentifierNameSyntax.One); ChecktIncrementExpression(node.Operand, ref binary, false); if (isSingleLine) { return operand.Assignment(binary); } else { if (isLocalVar) { CurBlock.Statements.Add(operand.Assignment(binary)); return operand; } else { var temp = GetTempIdentifier(); CurBlock.Statements.Add(new LuaLocalVariableDeclaratorSyntax(temp, binary)); CurBlock.Statements.Add(operand.Assignment(temp)); return temp; } } } private LuaSyntaxNode BuildPropertyPrefixUnaryExpression(bool isSingleLine, string operatorToken, LuaPropertyAdapterExpressionSyntax get, LuaPropertyAdapterExpressionSyntax set, PrefixUnaryExpressionSyntax node) { set.IsGetOrAdd = false; LuaExpressionSyntax left = get; ChecktIncrementExpression(node.Operand, ref left, true); LuaExpressionSyntax binary = left.Binary(operatorToken, LuaIdentifierNameSyntax.One); ChecktIncrementExpression(node.Operand, ref binary, false); if (isSingleLine) { set.ArgumentList.AddArgument(binary); return set; } else { var temp = GetTempIdentifier(); CurBlock.Statements.Add(new LuaLocalVariableDeclaratorSyntax(temp, binary)); set.ArgumentList.AddArgument(temp); CurBlock.Statements.Add(set); return temp; } } private LuaMemberAccessExpressionSyntax GetTempUnaryExpression(LuaMemberAccessExpressionSyntax memberAccess, out LuaLocalVariableDeclaratorSyntax localTemp) { var temp = GetTempIdentifier(); localTemp = new LuaLocalVariableDeclaratorSyntax(temp, memberAccess.Expression); return temp.MemberAccess(memberAccess.Name, memberAccess.IsObjectColon); } private LuaPropertyAdapterExpressionSyntax GetTempPropertyUnaryExpression(LuaPropertyAdapterExpressionSyntax propertyAdapter, out LuaLocalVariableDeclaratorSyntax localTemp) { var temp = GetTempIdentifier(); localTemp = new LuaLocalVariableDeclaratorSyntax(temp, propertyAdapter.Expression); return new LuaPropertyAdapterExpressionSyntax(temp, propertyAdapter.Name, propertyAdapter.IsObjectColon); } private bool IsNullablePrefixUnaryExpression(PrefixUnaryExpressionSyntax node, LuaExpressionSyntax operand, string operatorToken, out LuaExpressionSyntax result, LuaIdentifierNameSyntax method = null) { var type = semanticModel_.GetTypeInfo(node.Operand).Type; if (type.IsNullableType()) { var identifier = BuildNullableExpressionIdentifier(operand, new List<LuaExpressionSyntax>()); if (operatorToken != null) { result = identifier.And(new LuaPrefixUnaryExpressionSyntax(identifier, operatorToken)); } else { result = identifier.And(new LuaInvocationExpressionSyntax(method, identifier)); } return true; } result = null; return false; } public override LuaSyntaxNode VisitPrefixUnaryExpression(PrefixUnaryExpressionSyntax node) { SyntaxKind kind = node.Kind(); if (kind == SyntaxKind.IndexExpression) { var expression = VisitExpression(node.Operand); var v = semanticModel_.GetConstantValue(node.Operand); if (v.HasValue && (int)v.Value > 0) { return new LuaPrefixUnaryExpressionSyntax(expression, LuaSyntaxNode.Tokens.Sub); } return new LuaInvocationExpressionSyntax(LuaIdentifierNameSyntax.Index, expression, LuaIdentifierNameSyntax.True); } if (IsUserDefinedOperator(node, out var methodSymbol)) { var type = semanticModel_.GetTypeInfo(node.Operand).Type; if (type != null && type.IsNullableType()) { var arguments = new List<Func<LuaExpressionSyntax>>(); var identifiers = new List<LuaExpressionSyntax>(); arguments.Add(() => BuildNullableExpressionIdentifier(node.Operand, identifiers)); var operatorExpression = GetUserDefinedOperatorExpression(methodSymbol, arguments); return identifiers.First().And(operatorExpression); } return GetUserDefinedOperatorExpression(methodSymbol, node.Operand); } var operand = VisitExpression(node.Operand); switch (kind) { case SyntaxKind.PreIncrementExpression: case SyntaxKind.PreDecrementExpression: { bool isSingleLine = IsSingleLineUnary(node); string operatorToken = kind == SyntaxKind.PreIncrementExpression ? LuaSyntaxNode.Tokens.Plus : LuaSyntaxNode.Tokens.Sub; if (operand is LuaMemberAccessExpressionSyntax memberAccess) { if (memberAccess.Expression != LuaIdentifierNameSyntax.This) { memberAccess = GetTempUnaryExpression(memberAccess, out var localTemp); CurBlock.Statements.Add(localTemp); } return BuildPrefixUnaryExpression(isSingleLine, operatorToken, memberAccess, node); } else if (operand is LuaPropertyAdapterExpressionSyntax propertyAdapter) { if (propertyAdapter.Expression != null) { var getAdapter = GetTempPropertyUnaryExpression(propertyAdapter, out var localTemp); CurBlock.Statements.Add(localTemp); return BuildPropertyPrefixUnaryExpression(isSingleLine, operatorToken, getAdapter, getAdapter.GetClone(), node); } else { return BuildPropertyPrefixUnaryExpression(isSingleLine, operatorToken, propertyAdapter, propertyAdapter.GetClone(), node); } } else { bool isLocalVar = false; if (!isSingleLine) { SymbolKind symbolKind = semanticModel_.GetSymbolInfo(node.Operand).Symbol.Kind; if (symbolKind == SymbolKind.Parameter || symbolKind == SymbolKind.Local) { isLocalVar = true; } } return BuildPrefixUnaryExpression(isSingleLine, operatorToken, operand, node, isLocalVar); } } case SyntaxKind.PointerIndirectionExpression: { var identifier = new LuaPropertyOrEventIdentifierNameSyntax(true, LuaIdentifierNameSyntax.Empty); return new LuaPropertyAdapterExpressionSyntax(operand, identifier, true); } case SyntaxKind.BitwiseNotExpression: { if (IsLuaClassic) { if (IsNullablePrefixUnaryExpression(node, operand, null, out var result, LuaIdentifierNameSyntax.BitNot)) { return result; } return LuaIdentifierNameSyntax.BitNot.Invocation(operand); } else if (IsPreventDebug && IsNullablePrefixUnaryExpression(node, operand, LuaSyntaxNode.Tokens.BitNot, out var result)) { return result; } break; } case SyntaxKind.UnaryPlusExpression: { return operand; } case SyntaxKind.UnaryMinusExpression: { if (operand is LuaLiteralExpressionSyntax e && e.Text == "0") { return operand; } if (IsPreventDebug && IsNullablePrefixUnaryExpression(node, operand, LuaSyntaxNode.Tokens.Sub, out var result)) { return result; } break; } case SyntaxKind.LogicalNotExpression: { var symbol = semanticModel_.GetTypeInfo(node.Operand).Type; if (symbol != null && symbol.IsNullableType() && symbol.IsBoolType(true)) { var temp = GetTempIdentifier(); CurBlock.AddStatement(new LuaLocalVariableDeclaratorSyntax(temp)); var identifier = BuildNullableExpressionIdentifier(operand, new List<LuaExpressionSyntax>()); var ifStatement = new LuaIfStatementSyntax(identifier.NotEquals(LuaIdentifierNameSyntax.Nil)); ifStatement.Body.AddStatement(temp.Assignment(new LuaPrefixUnaryExpressionSyntax(identifier, LuaSyntaxNode.Tokens.Not))); CurBlock.AddStatement(ifStatement); return temp; } break; } } var unaryExpression = new LuaPrefixUnaryExpressionSyntax(operand, GetOperatorToken(node.OperatorToken)); return unaryExpression; } private LuaSyntaxNode BuildPostfixUnaryExpression(bool isSingleLine, string operatorToken, LuaExpressionSyntax operand, PostfixUnaryExpressionSyntax node) { if (isSingleLine) { var left = operand; ChecktIncrementExpression(node.Operand, ref left, true); LuaExpressionSyntax binary = left.Binary(operatorToken, LuaIdentifierNameSyntax.One); ChecktIncrementExpression(node.Operand, ref binary, false); return operand.Assignment(binary); } else { var temp = GetTempIdentifier(); CurBlock.Statements.Add(new LuaLocalVariableDeclaratorSyntax(temp, operand)); LuaExpressionSyntax left = temp; ChecktIncrementExpression(node.Operand, ref left, true); LuaExpressionSyntax binary = left.Binary(operatorToken, LuaIdentifierNameSyntax.One); ChecktIncrementExpression(node.Operand, ref binary, false); CurBlock.Statements.Add(operand.Assignment(binary)); return temp; } } private LuaSyntaxNode BuildPropertyPostfixUnaryExpression(bool isSingleLine, string operatorToken, LuaPropertyAdapterExpressionSyntax get, LuaPropertyAdapterExpressionSyntax set, PostfixUnaryExpressionSyntax node) { set.IsGetOrAdd = false; if (isSingleLine) { LuaExpressionSyntax left = get; ChecktIncrementExpression(node.Operand, ref left, true); LuaExpressionSyntax binary = left.Binary(operatorToken, LuaIdentifierNameSyntax.One); ChecktIncrementExpression(node.Operand, ref binary, false); set.ArgumentList.AddArgument(binary); return set; } else { var temp = GetTempIdentifier(); CurBlock.Statements.Add(new LuaLocalVariableDeclaratorSyntax(temp, get)); LuaExpressionSyntax left = temp; ChecktIncrementExpression(node.Operand, ref left, true); LuaExpressionSyntax binary = left.Binary(operatorToken, LuaIdentifierNameSyntax.One); ChecktIncrementExpression(node.Operand, ref binary, false); set.ArgumentList.AddArgument(binary); CurBlock.AddStatement(set); return temp; } } public override LuaSyntaxNode VisitPostfixUnaryExpression(PostfixUnaryExpressionSyntax node) { SyntaxKind kind = node.Kind(); if (kind != SyntaxKind.PostIncrementExpression && kind != SyntaxKind.PostDecrementExpression) { throw new NotSupportedException(); } bool isSingleLine = IsSingleLineUnary(node); string operatorToken = kind == SyntaxKind.PostIncrementExpression ? LuaSyntaxNode.Tokens.Plus : LuaSyntaxNode.Tokens.Sub; var operand = node.Operand.AcceptExpression(this); if (operand is LuaMemberAccessExpressionSyntax memberAccess) { if (memberAccess.Expression != LuaIdentifierNameSyntax.This) { memberAccess = GetTempUnaryExpression(memberAccess, out var localTemp); CurBlock.Statements.Add(localTemp); } return BuildPostfixUnaryExpression(isSingleLine, operatorToken, memberAccess, node); } else if (operand is LuaPropertyAdapterExpressionSyntax propertyAdapter) { if (propertyAdapter.Expression != null) { var getAdapter = GetTempPropertyUnaryExpression(propertyAdapter, out var localTemp); CurBlock.Statements.Add(localTemp); return BuildPropertyPostfixUnaryExpression(isSingleLine, operatorToken, getAdapter, getAdapter.GetClone(), node); } else { return BuildPropertyPostfixUnaryExpression(isSingleLine, operatorToken, propertyAdapter, propertyAdapter.GetClone(), node); } } else { return BuildPostfixUnaryExpression(isSingleLine, operatorToken, operand, node); } } public override LuaSyntaxNode VisitContinueStatement(ContinueStatementSyntax node) { bool isWithinTry = IsParnetTryStatement(node); if (isWithinTry) { var check = (LuaCheckLoopControlExpressionSyntax)CurFunction; check.HasContinue = true; } return new LuaContinueAdapterStatementSyntax(isWithinTry); } private static bool IsLastBreakStatement(LuaStatementSyntax lastStatement) { if (lastStatement == LuaBreakStatementSyntax.Instance) { return true; } if (lastStatement is LuaContinueAdapterStatementSyntax) { return true; } if (lastStatement is LuaLabeledStatement labeledStatement && IsLastBreakStatement(labeledStatement.Statement)) { return true; } return false; } private void VisitLoopBody(StatementSyntax bodyStatement, LuaBlockSyntax block) { bool hasContinue = IsContinueExists(bodyStatement); if (hasContinue) { // http://lua-users.org/wiki/ContinueProposal var continueIdentifier = LuaIdentifierNameSyntax.Continue; block.Statements.Add(new LuaLocalVariableDeclaratorSyntax(continueIdentifier)); LuaRepeatStatementSyntax repeatStatement = new LuaRepeatStatementSyntax(LuaIdentifierNameSyntax.One); WriteStatementOrBlock(bodyStatement, repeatStatement.Body); var lastStatement = repeatStatement.Body.Statements.Last(); bool isLastFinal = lastStatement is LuaBaseReturnStatementSyntax || IsLastBreakStatement(lastStatement); if (!isLastFinal) { repeatStatement.Body.Statements.Add(continueIdentifier.Assignment(LuaIdentifierNameSyntax.True)); } block.Statements.Add(repeatStatement); LuaIfStatementSyntax IfStatement = new LuaIfStatementSyntax(new LuaPrefixUnaryExpressionSyntax(continueIdentifier, LuaSyntaxNode.Tokens.Not)); IfStatement.Body.Statements.Add(LuaBreakStatementSyntax.Instance); block.Statements.Add(IfStatement); } else { WriteStatementOrBlock(bodyStatement, block); } } private void CheckForeachCast(LuaIdentifierNameSyntax identifier, ForEachStatementSyntax node, LuaForInStatementSyntax forInStatement, bool isAsync) { var sourceType = semanticModel_.GetTypeInfo(node.Expression).Type; var targetType = semanticModel_.GetTypeInfo(node.Type).Type; bool hasCast = false; var elementType = !isAsync ? sourceType.GetIEnumerableElementType() : sourceType.GetIAsyncEnumerableElementType(); if (elementType != null) { if (!elementType.EQ(targetType) && !elementType.Is(targetType)) { hasCast = true; } } else { if (targetType.SpecialType != SpecialType.System_Object) { hasCast = true; } } if (hasCast) { var cast = new LuaInvocationExpressionSyntax(LuaIdentifierNameSyntax.Cast, GetTypeName(targetType), identifier); forInStatement.Body.AddStatement(identifier.Assignment(cast)); } } public override LuaSyntaxNode VisitForEachStatement(ForEachStatementSyntax node) { LuaIdentifierNameSyntax identifier = node.Identifier.ValueText; CheckLocalVariableName(ref identifier, node); var expression = node.Expression.AcceptExpression(this); bool isAsync = node.AwaitKeyword.IsKind(SyntaxKind.AwaitKeyword); var forInStatement = new LuaForInStatementSyntax(identifier, expression, isAsync); CheckForeachCast(identifier, node, forInStatement, isAsync); VisitLoopBody(node.Statement, forInStatement.Body); return forInStatement; } public override LuaSyntaxNode VisitForEachVariableStatement(ForEachVariableStatementSyntax node) { var temp = GetTempIdentifier(); var expression = node.Expression.AcceptExpression(this); var forInStatement = new LuaForInStatementSyntax(temp, expression); var left = node.Variable.AcceptExpression(this); var sourceType = semanticModel_.GetTypeInfo(node.Expression).Type; var elementType = sourceType.GetIEnumerableElementType(); var right = BuildDeconstructExpression(elementType, temp, node.Expression); forInStatement.Body.AddStatement(left.Assignment(right)); VisitLoopBody(node.Statement, forInStatement.Body); return forInStatement; } private LuaWhileStatementSyntax BuildWhileStatement(ExpressionSyntax nodeCondition, StatementSyntax nodeStatement) { LuaBlockSyntax conditionBody = new LuaBlockSyntax(); PushBlock(conditionBody); var condition = nodeCondition != null ? VisitExpression(nodeCondition) : LuaIdentifierNameSyntax.True; PopBlock(); LuaWhileStatementSyntax whileStatement; if (conditionBody.Statements.Count == 0) { whileStatement = new LuaWhileStatementSyntax(condition); } else { whileStatement = new LuaWhileStatementSyntax(LuaIdentifierNameSyntax.True); if (condition is LuaBinaryExpressionSyntax) { condition = condition.Parenthesized(); } LuaIfStatementSyntax ifStatement = new LuaIfStatementSyntax(new LuaPrefixUnaryExpressionSyntax(condition, LuaSyntaxNode.Tokens.Not)); ifStatement.Body.AddStatement(LuaBreakStatementSyntax.Instance); whileStatement.Body.Statements.AddRange(conditionBody.Statements); whileStatement.Body.Statements.Add(ifStatement); } VisitLoopBody(nodeStatement, whileStatement.Body); return whileStatement; } public override LuaSyntaxNode VisitWhileStatement(WhileStatementSyntax node) { return BuildWhileStatement(node.Condition, node.Statement); } public override LuaSyntaxNode VisitForStatement(ForStatementSyntax node) { var numericalForStatement = GetNumericalForStatement(node); if (numericalForStatement != null) { return numericalForStatement; } LuaBlockSyntax forBlock = new LuaBlockStatementSyntax(); PushBlock(forBlock); if (node.Declaration != null) { forBlock.AddStatement(node.Declaration.Accept<LuaVariableDeclarationSyntax>(this)); } var initializers = node.Initializers.Select(i => i.AcceptExpression(this)); forBlock.AddStatements(initializers); var whileStatement = BuildWhileStatement(node.Condition, node.Statement); PushBlock(whileStatement.Body); var incrementors = node.Incrementors.Select(i => i.AcceptExpression(this)); whileStatement.Body.AddStatements(incrementors); PopBlock(); forBlock.Statements.Add(whileStatement); PopBlock(); return forBlock; } public override LuaSyntaxNode VisitDoStatement(DoStatementSyntax node) { LuaBlockSyntax body = new LuaBlockSyntax(); PushBlock(body); VisitLoopBody(node.Statement, body); var condition = VisitExpression(node.Condition); if (condition is LuaBinaryExpressionSyntax) { condition = condition.Parenthesized(); } var newCondition = new LuaPrefixUnaryExpressionSyntax(condition, LuaSyntaxNode.Tokens.Not); PopBlock(); return new LuaRepeatStatementSyntax(newCondition, body); } public override LuaSyntaxNode VisitYieldStatement(YieldStatementSyntax node) { var curMehod = CurMethodInfoOrNull; curMehod.HasYield = true; if (node.IsKind(SyntaxKind.YieldBreakStatement)) { return new LuaReturnStatementSyntax(); } else { string yieldToken = node.YieldKeyword.ValueText; var expression = node.Expression.AcceptExpression(this); LuaExpressionSyntax targetMethod; if (curMehod.Symbol.IsAsync) { targetMethod = LuaIdentifierNameSyntax.Async.MemberAccess(yieldToken, true); } else { targetMethod = LuaIdentifierNameSyntax.System.MemberAccess(yieldToken); } return new LuaExpressionStatementSyntax(targetMethod.Invocation(expression)); } } public override LuaSyntaxNode VisitParenthesizedExpression(ParenthesizedExpressionSyntax node) { var expression = node.Expression.AcceptExpression(this); if (expression is LuaIdentifierNameSyntax || expression is LuaMemberAccessExpressionSyntax) { return expression; } CheckPrevIsInvokeStatement(node); return expression.Parenthesized(); } /// <summary> /// http://lua-users.org/wiki/TernaryOperator /// </summary> public override LuaSyntaxNode VisitConditionalExpression(ConditionalExpressionSyntax node) { bool mayBeNullOrFalse = MayBeNullOrFalse(node.WhenTrue); if (mayBeNullOrFalse) { var temp = GetTempIdentifier(); var condition = VisitExpression(node.Condition); LuaIfStatementSyntax ifStatement = new LuaIfStatementSyntax(condition); PushBlock(ifStatement.Body); var whenTrue = VisitExpression(node.WhenTrue); PopBlock(); ifStatement.Body.AddStatement(temp.Assignment(whenTrue)); LuaElseClauseSyntax elseClause = new LuaElseClauseSyntax(); PushBlock(elseClause.Body); var whenFalse = VisitExpression(node.WhenFalse); PopBlock(); elseClause.Body.AddStatement(temp.Assignment(whenFalse)); ifStatement.Else = elseClause; CurBlock.AddStatement(new LuaLocalVariableDeclaratorSyntax(temp)); CurBlock.AddStatement(ifStatement); return temp; } else { LuaExpressionSyntax Accept(ExpressionSyntax expressionNode) { var expression = VisitExpression(expressionNode); return expression is LuaBinaryExpressionSyntax ? expression.Parenthesized() : expression; } var condition = Accept(node.Condition); var whenTrue = Accept(node.WhenTrue); var whenFalse = Accept(node.WhenFalse); return condition.And(whenTrue).Or(whenFalse); } } public override LuaSyntaxNode VisitGotoStatement(GotoStatementSyntax node) { if (node.CaseOrDefaultKeyword.IsKind(SyntaxKind.CaseKeyword)) { const string kCaseLabel = "caseLabel"; var switchStatement = switchs_.Peek(); int caseIndex = GetCaseLabelIndex(node); var labelIdentifier = switchStatement.CaseLabels.GetOrDefault(caseIndex); if (labelIdentifier == null) { string uniqueName = GetUniqueIdentifier(kCaseLabel + caseIndex, node); labelIdentifier = uniqueName; switchStatement.CaseLabels.Add(caseIndex, labelIdentifier); } return new LuaGotoCaseAdapterStatement(labelIdentifier); } else if (node.CaseOrDefaultKeyword.IsKind(SyntaxKind.DefaultKeyword)) { const string kDefaultLabel = "defaultLabel"; var switchStatement = switchs_.Peek(); if (switchStatement.DefaultLabel == null) { string identifier = GetUniqueIdentifier(kDefaultLabel, node); switchStatement.DefaultLabel = identifier; } return new LuaGotoCaseAdapterStatement(switchStatement.DefaultLabel); } else { var identifier = node.Expression.Accept<LuaIdentifierNameSyntax>(this); return new LuaGotoStatement(identifier); } } public override LuaSyntaxNode VisitLabeledStatement(LabeledStatementSyntax node) { LuaIdentifierNameSyntax identifier = node.Identifier.ValueText; var statement = node.Statement.Accept<LuaStatementSyntax>(this); return new LuaLabeledStatement(identifier, statement); } public override LuaSyntaxNode VisitEmptyStatement(EmptyStatementSyntax node) { return LuaStatementSyntax.Empty; } private LuaExpressionSyntax BuildEnumCastExpression(LuaExpressionSyntax expression, ITypeSymbol originalType, ITypeSymbol targetType) { if (targetType.TypeKind == TypeKind.Enum) { LuaExpressionSyntax result = null; var targetEnumUnderlyingType = ((INamedTypeSymbol)targetType).EnumUnderlyingType; if (originalType.TypeKind == TypeKind.Enum || originalType.IsCastIntegerType()) { var originalIntegerType = originalType.TypeKind == TypeKind.Enum ? ((INamedTypeSymbol)originalType).EnumUnderlyingType : originalType; if (targetEnumUnderlyingType.IsNumberTypeAssignableFrom(originalIntegerType)) { result = expression; } else { result = GetCastToNumberExpression(expression, targetEnumUnderlyingType, false); } } else if (originalType.IsDoubleOrFloatType(false)) { result = GetCastToNumberExpression(expression, targetEnumUnderlyingType, true); } if (result != null) { if (!generator_.IsConstantEnum(targetType) && !originalType.EQ(targetType)) { result = GetTypeName(targetType).Invocation(expression); } return result; } } else if (originalType.TypeKind == TypeKind.Enum) { var originalEnumUnderlyingType = ((INamedTypeSymbol)originalType).EnumUnderlyingType; if (targetType.IsCastIntegerType()) { if (!generator_.IsConstantEnum(originalType)) { return GetEnumNoConstantToNumberExpression(expression, targetType); } if (targetType.IsNumberTypeAssignableFrom(originalEnumUnderlyingType)) { return expression; } return GetCastToNumberExpression(expression, targetType, false); } else if (targetType.IsDoubleOrFloatType(false)) { return expression; } } return null; } private LuaExpressionSyntax BuildNumberCastExpression(LuaExpressionSyntax expression, ITypeSymbol originalType, ITypeSymbol targetType) { if (targetType.IsCastIntegerType()) { if (originalType.IsCastIntegerType()) { if (targetType.IsNumberTypeAssignableFrom(originalType)) { return expression; } return GetCastToNumberExpression(expression, targetType, false); } else if (originalType.IsDoubleOrFloatType(false)) { return GetCastToNumberExpression(expression, targetType, true); } } else if (originalType.IsCastIntegerType()) { if (targetType.IsDoubleOrFloatType(false)) { return expression; } } else if (targetType.SpecialType == SpecialType.System_Single && originalType.SpecialType == SpecialType.System_Double) { return GetCastToNumberExpression(expression, targetType, true); } return null; } private LuaExpressionSyntax BuildEnumAndNumberCastExpression(LuaExpressionSyntax expression, ITypeSymbol originalType, ITypeSymbol targetType) { return BuildEnumCastExpression(expression, originalType, targetType) ?? BuildNumberCastExpression(expression, originalType, targetType); } private LuaExpressionSyntax BuildNullableCastExpression(LuaExpressionSyntax expression, ITypeSymbol originalType, ITypeSymbol targetType) { var targetNullableElemetType = targetType.NullableElemetType(); var originalNullableElemetType = originalType.NullableElemetType(); if (targetNullableElemetType != null) { if (originalNullableElemetType != null) { bool isIdentifier = false; LuaIdentifierNameSyntax identifier; if (expression is LuaIdentifierNameSyntax identifierName) { identifier = identifierName; isIdentifier = true; } else { identifier = GetTempIdentifier(); } var castExpression = BuildEnumAndNumberCastExpression(identifier, originalNullableElemetType, targetNullableElemetType); if (castExpression != null) { if (castExpression == identifier) { return expression; } if (!isIdentifier) { CurBlock.AddStatement(new LuaLocalVariableDeclaratorSyntax(identifier, expression)); } return identifier.And(castExpression); } } else { return BuildEnumAndNumberCastExpression(expression, originalType, targetNullableElemetType); } } else if (originalNullableElemetType != null) { var explicitMethod = (IMethodSymbol)originalType.GetMembers("op_Explicit").First(); expression = BuildConversionExpression(explicitMethod, expression); return BuildEnumAndNumberCastExpression(expression, originalNullableElemetType, targetType); } return null; } public override LuaSyntaxNode VisitCastExpression(CastExpressionSyntax node) { var constExpression = GetConstExpression(node); if (constExpression != null) { return constExpression; } var targetType = semanticModel_.GetTypeInfo(node.Type).Type; var expression = node.Expression.AcceptExpression(this); if (targetType.SpecialType == SpecialType.System_Object || targetType.Kind == SymbolKind.DynamicType) { return expression; } var originalType = semanticModel_.GetTypeInfo(node.Expression).Type; if (originalType == null) { Contract.Assert(targetType.IsDelegateType()); return expression; } if (originalType.Is(targetType)) { return expression; } var result = BuildEnumAndNumberCastExpression(expression, originalType, targetType); if (result != null) { return result; } result = BuildNullableCastExpression(expression, originalType, targetType); if (result != null) { return result; } var explicitSymbol = (IMethodSymbol)semanticModel_.GetSymbolInfo(node).Symbol; if (explicitSymbol != null) { return BuildConversionExpression(explicitSymbol, expression); } return BuildCastExpression(targetType, expression); } private LuaExpressionSyntax BuildCastExpression(ITypeSymbol type, LuaExpressionSyntax expression) { var typeExpression = GetTypeName(type.IsNullableType() ? type.NullableElemetType() : type); var invocation = new LuaInvocationExpressionSyntax(LuaIdentifierNameSyntax.Cast, typeExpression, expression); if (type.IsNullableType()) { invocation.AddArgument(LuaIdentifierNameSyntax.True); } return invocation; } private LuaExpressionSyntax GetEnumNoConstantToNumberExpression(LuaExpressionSyntax expression, ITypeSymbol targetType) { string methodName = "System.Convert.To" + targetType.Name; return new LuaInvocationExpressionSyntax(methodName, expression); } private LuaExpressionSyntax GetCastToNumberExpression(LuaExpressionSyntax expression, ITypeSymbol targetType, bool isFromFloat) { if (expression is LuaParenthesizedExpressionSyntax parenthesizedExpression) { expression = parenthesizedExpression.Expression; } string name = (isFromFloat ? "To" : "to") + (targetType.SpecialType == SpecialType.System_Char ? "UInt16" : targetType.Name); var invocation = LuaIdentifierNameSyntax.System.MemberAccess(name).Invocation(expression); if (IsCurChecked) { invocation.AddArgument(LuaIdentifierNameSyntax.True); } return invocation; } public override LuaSyntaxNode VisitCheckedStatement(CheckedStatementSyntax node) { bool isChecked = node.Keyword.Kind() == SyntaxKind.CheckedKeyword; PushChecked(isChecked); var statements = new LuaStatementListSyntax(); statements.Statements.Add(new LuaShortCommentStatement(" " + node.Keyword.ValueText)); var block = node.Block.Accept<LuaStatementSyntax>(this); statements.Statements.Add(block); PopChecked(); return statements; } public override LuaSyntaxNode VisitCheckedExpression(CheckedExpressionSyntax node) { bool isChecked = node.Keyword.Kind() == SyntaxKind.CheckedKeyword; PushChecked(isChecked); var expression = node.Expression.Accept(this); PopChecked(); return expression; } public override LuaSyntaxNode VisitNullableType(NullableTypeSyntax node) { var elementType = node.ElementType.AcceptExpression(this); return new LuaInvocationExpressionSyntax(LuaIdentifierNameSyntax.NullableType, elementType); } } }
44.212783
253
0.672984
[ "Apache-2.0" ]
HongXiao/CSharp.lua
CSharp.lua/LuaSyntaxNodeTransform.cs
226,900
C#
using System; namespace ApiService.Contracts.ManagerApi { public interface GetArchivedOrder { public Guid OrderId { get; set; } } }
17.333333
41
0.660256
[ "MIT" ]
konvovden/masstransit-demo
src/Contracts/ApiService.Contracts/ManagerApi/GetArchivedOrder.cs
158
C#
using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using LinqToDB.Common; namespace LinqToDB.SqlQuery { public interface IReadOnlyParameterValues { bool TryGetValue(SqlParameter parameter, [NotNullWhen(true)] out SqlParameterValue? value); } public class SqlParameterValues : IReadOnlyParameterValues { public static IReadOnlyParameterValues Empty = new SqlParameterValues(); private Dictionary<SqlParameter, SqlParameterValue>? _valuesByParameter; private Dictionary<int, SqlParameterValue>? _valuesByAccessor; public void AddValue(SqlParameter parameter, object? value, DbDataType dbDataType) { _valuesByParameter ??= new Dictionary<SqlParameter, SqlParameterValue>(); var parameterValue = new SqlParameterValue(value, dbDataType); _valuesByParameter.Remove(parameter); _valuesByParameter.Add(parameter, parameterValue); if (parameter.AccessorId != null) { _valuesByAccessor ??= new Dictionary<int, SqlParameterValue>(); _valuesByAccessor.Remove(parameter.AccessorId.Value); _valuesByAccessor.Add(parameter.AccessorId.Value, parameterValue); } } public void SetValue(SqlParameter parameter, object? value) { _valuesByParameter ??= new Dictionary<SqlParameter, SqlParameterValue>(); if (!_valuesByParameter.TryGetValue(parameter, out var parameterValue)) { parameterValue = new SqlParameterValue(value, parameter.Type); _valuesByParameter.Add(parameter, parameterValue); } else { _valuesByParameter.Remove(parameter); _valuesByParameter.Add(parameter, new SqlParameterValue(value, parameterValue.DbDataType)); } if (parameter.AccessorId != null) { _valuesByAccessor ??= new Dictionary<int, SqlParameterValue>(); if (!_valuesByAccessor.TryGetValue(parameter.AccessorId.Value, out parameterValue)) { parameterValue = new SqlParameterValue(value, parameter.Type); _valuesByAccessor.Add(parameter.AccessorId.Value, parameterValue); } else { _valuesByAccessor.Remove(parameter.AccessorId.Value); _valuesByAccessor.Add(parameter.AccessorId.Value, new SqlParameterValue(value, parameterValue.DbDataType)); } } } public bool TryGetValue(SqlParameter parameter, [NotNullWhen(true)] out SqlParameterValue? value) { value = null; if (_valuesByParameter?.TryGetValue(parameter, out value) == false && parameter.AccessorId != null && _valuesByAccessor?.TryGetValue(parameter.AccessorId.Value, out value) == false) { return false; } return value != null; } } }
33.658228
122
0.727341
[ "MIT" ]
Corey-M/linq2db
Source/LinqToDB/SqlQuery/SqlParameterValues.cs
2,583
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Reflection; [assembly: System.Reflection.AssemblyCompanyAttribute("08. BalancedParentheses")] [assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")] [assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")] [assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")] [assembly: System.Reflection.AssemblyProductAttribute("08. BalancedParentheses")] [assembly: System.Reflection.AssemblyTitleAttribute("08. BalancedParentheses")] [assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")] // Generated by the MSBuild WriteCodeFragment class.
42.458333
81
0.654563
[ "MIT" ]
georgivv7/C-Sharp-Advanced-SoftUni
StacksAndQueues-Exercise/08. BalancedParentheses/obj/Debug/netcoreapp3.1/08. BalancedParentheses.AssemblyInfo.cs
1,019
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using TMPro; using UnityEngine.SceneManagement; public class StoreManager : MonoBehaviour { #region Public Variables public TMP_Text coffeeQuantityText, buyCoffeeText, buyWeaponText, weaponInfoText; [Space] public Image weaponImage; public Guns[] gunVetor; public TMP_Text[] gunsText; #endregion #region Private Variables private int coffeeQuant = 1; #endregion void Start() { buyCoffeeText.text = "Buy " + coffeeQuant + " coffee(s) for " + Helper.WattsNomenclature(coffeeQuant * 500); for (int i = 0; i < gunVetor.Length; i++) { ChangeWeaponText(i); } } #region Public Methods public void BuyAntenna(int metalQ) { if (SaveManager.Instance.state.metalAmount >= metalQ) { SaveManager.Instance.state.endGameOcurred = true; StartCoroutine("EndGameCredits"); } } IEnumerator EndGameCredits() { yield return new WaitForSecondsRealtime(5f); SceneManager.LoadScene("CongratsForConclusion"); } public void UpdateCoffeeQuantity(int quant) { if (coffeeQuant + quant > 0) coffeeQuant += quant; coffeeQuantityText.text = coffeeQuant.ToString(); buyCoffeeText.text = "Comprar " + coffeeQuant + " café(s) por " + Helper.WattsNomenclature(coffeeQuant * 500); } public void RechargeWeapon() { if (SaveManager.Instance.state.wattsStored > 0) { float wattsToRecharge = ShootController.Instance.gun.energyStored - ShootController.Instance.energyStored; if (wattsToRecharge > 0) { ShootController.Instance.energyStored += wattsToRecharge; SaveManager.Instance.state.wattsStored -= wattsToRecharge; if (SaveManager.Instance.state.wattsStored < 0) { SaveManager.Instance.state.wattsStored = Mathf.Abs(SaveManager.Instance.state.wattsStored); ShootController.Instance.energyStored -= SaveManager.Instance.state.wattsStored; SaveManager.Instance.state.wattsStored -= SaveManager.Instance.state.wattsStored; } } } } public void BuyPortableRecharge() { if (SaveManager.Instance.state.wattsStored >= ShootController.Instance.gun.energyStored && SaveManager.Instance.state.recharges < 3) { SaveManager.Instance.state.recharges++; SaveManager.Instance.state.wattsStored -= ShootController.Instance.gun.energyStored; } } public void BuyCoffe(float cost) { if (SaveManager.Instance.state.wattsStored >= cost * coffeeQuant) { SaveManager.Instance.state.coffeeQuantity += coffeeQuant; SaveManager.Instance.state.wattsStored -= cost * coffeeQuant; } } public void ChangeWeaponText(int ID) { Guns gun = gunVetor[ID]; gunsText[ID].text = gun.name; } int currentWeaponID; public void SelectWeapon(int ID) { currentWeaponID = ID; Guns gun = gunVetor[currentWeaponID]; float weaponPrice = gun.gunPrice; weaponImage.sprite = gun.gunIcon; string isAuto = "Sim"; if(!gun.isAutomatic) isAuto = "Não"; weaponInfoText.text = "Automatico: "+ isAuto + "\nEnergia: "+ Helper.WattsNomenclature(weaponPrice) + "\nDano: " + Mathf.Abs(gun.gunDamage) + "\nTaxa de tiro: " + gun.fireRate + " por segundo"; if (SaveManager.Instance.state.gunIdUnlocked[gun.gunId]) { buyWeaponText.text = "Equipar"; } else { buyWeaponText.text = Helper.WattsNomenclature(weaponPrice); } } public void BuyWeapon() { int ID = currentWeaponID; Guns gun = gunVetor[ID]; string weaponName = gun.gunName; float weaponPrice = gun.gunPrice; if (SaveManager.Instance.state.gunIdUnlocked[gun.gunId]) { Debug.Log("Equipando"); ShootController.Instance.EquipWeapon(gun); SaveManager.Instance.state.equipedGunId = gun.gunId; } else { Debug.Log("Comprando"); if (SaveManager.Instance.state.wattsStored >= weaponPrice) { SaveManager.Instance.state.wattsStored -= weaponPrice; SaveManager.Instance.state.gunIdUnlocked[gun.gunId] = true; ShootController.Instance.EquipWeapon(gun); SaveManager.Instance.state.equipedGunId = gun.gunId; } } } #endregion }
30.884615
140
0.611249
[ "MIT" ]
Cillor/ForestDefense
Assets/Scripts/Menu/StoreManager.cs
4,822
C#
using System; namespace ConcatenateData { class Program { static void Main(string[] args) { string firstName = Console.ReadLine(); string lastName = Console.ReadLine(); int age = int.Parse(Console.ReadLine()); string city = Console.ReadLine(); Console.WriteLine("You are " + firstName +" "+ lastName + ", a " + age + "-years old person from " + city+"."); } } }
21.727273
125
0.520921
[ "MIT" ]
VladimirDikovski/Programing-Bassic
simpli operation/ConcatenateData/ConcatenateData/Program.cs
480
C#
using System; using System.Collections.Generic; using System.Linq; namespace BeFaster.Runner.Utils { public struct Optional<T> where T : class { private readonly IEnumerable<T> values; public static Optional<T> Some(T value) { if (value == null) { throw new InvalidOperationException(); } return new Optional<T>(new[] {value}); } public static Optional<T> OfNullable(T value) => value == null ? None : Some(value); public static Optional<T> None => new Optional<T>(new T[0]); public bool HasValue => values != null && values.Any(); public T OrElse(T other) => HasValue ? Value : other; public T OrElseThrow(Func<Exception> exceptionSupplier) => HasValue ? Value : throw exceptionSupplier(); public T Value { get { if (!HasValue) { throw new InvalidOperationException("Optional does not have a value"); } return values.Single(); } } private Optional(IEnumerable<T> values) { this.values = values; } } }
25.98
113
0.505774
[ "Apache-2.0" ]
DPNT-Sourcecode/CHK-alip01
src/BeFaster.Runner/Utils/Optional.cs
1,301
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the ec2-2016-11-15.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.EC2.Model { /// <summary> /// This is the response object from the CreateLaunchTemplateVersion operation. /// </summary> public partial class CreateLaunchTemplateVersionResponse : AmazonWebServiceResponse { private LaunchTemplateVersion _launchTemplateVersion; private ValidationWarning _warning; /// <summary> /// Gets and sets the property LaunchTemplateVersion. /// <para> /// Information about the launch template version. /// </para> /// </summary> public LaunchTemplateVersion LaunchTemplateVersion { get { return this._launchTemplateVersion; } set { this._launchTemplateVersion = value; } } // Check to see if LaunchTemplateVersion property is set internal bool IsSetLaunchTemplateVersion() { return this._launchTemplateVersion != null; } /// <summary> /// Gets and sets the property Warning. /// <para> /// If the new version of the launch template contains parameters or parameter combinations /// that are not valid, an error code and an error message are returned for each issue /// that's found. /// </para> /// </summary> public ValidationWarning Warning { get { return this._warning; } set { this._warning = value; } } // Check to see if Warning property is set internal bool IsSetWarning() { return this._warning != null; } } }
32.090909
101
0.647916
[ "Apache-2.0" ]
NGL321/aws-sdk-net
sdk/src/Services/EC2/Generated/Model/CreateLaunchTemplateVersionResponse.cs
2,471
C#
using System.Windows; using Microsoft.Xaml.Behaviors; namespace CoreTools.WPF.Behaviors { public static class Interactions { public static BehaviorsCollection GetBehaviors(DependencyObject obj) { return (BehaviorsCollection) obj.GetValue(BehaviorsProperty); } public static void SetBehaviors(DependencyObject obj, BehaviorsCollection value) { obj.SetValue(BehaviorsProperty, value); } public static readonly DependencyProperty BehaviorsProperty = DependencyProperty.RegisterAttached("Behaviors", typeof(BehaviorsCollection), typeof(Interactions), new UIPropertyMetadata(null, OnPropertyBehaviorsChanged)); private static void OnPropertyBehaviorsChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { if (e.NewValue is not BehaviorsCollection behaviorsCollection) return; var behaviors = Interaction.GetBehaviors(d); foreach (var behavior in behaviorsCollection) behaviors.Add(behavior); } public static TriggersCollection GetTriggers(DependencyObject obj) { return (TriggersCollection) obj.GetValue(TriggersProperty); } public static void SetTriggers(DependencyObject obj, TriggersCollection value) { obj.SetValue(TriggersProperty, value); } public static readonly DependencyProperty TriggersProperty = DependencyProperty.RegisterAttached("Triggers", typeof(TriggersCollection), typeof(Interactions), new UIPropertyMetadata(null, OnPropertyTriggersChanged)); private static void OnPropertyTriggersChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { if (e.NewValue is not TriggersCollection triggersCollection) return; var triggers = Interaction.GetTriggers(d); foreach (var trigger in triggersCollection) triggers.Add(trigger); } } }
37.553571
112
0.668569
[ "MIT" ]
tnunnink/CoreTools.WPF
src/CoreTools.WPF/Behaviors/Interactions.cs
2,105
C#
using System; using System.Collections.Generic; using Cosmos.Core; using Cosmos.Debug.Kernel; using Cosmos.HAL.BlockDevice; using Cosmos.HAL.Debug; using Cosmos.HAL.Network; namespace Cosmos.HAL; public static class Global { public static readonly Debugger mDebugger = new("HAL", "Global"); public static PIT PIT = new(); // Must be static init, other static inits rely on it not being null public static TextScreenBase TextScreen = new TextScreen(); public static PCI Pci; public static readonly PS2Controller PS2Controller = new(); /// <summary> /// Check if CPU interrupts are enabled. /// </summary> public static bool InterruptsEnabled => CPU.mInterruptsEnabled; // TODO: continue adding exceptions to the list, as HAL and Core would be documented. /// <summary> /// Init <see cref="Global" /> instance. /// </summary> /// <param name="textScreen">Text screen.</param> /// <exception cref="System.IO.IOException">Thrown on IO error.</exception> public static void Init(TextScreenBase textScreen, bool InitScrollWheel, bool InitPS2, bool InitNetwork, bool IDEInit) { if (textScreen != null) { TextScreen = textScreen; } mDebugger.Send("Before Core.Global.Init"); Core.Global.Init(); //TODO Redo this - Global init should be other. // Move PCI detection to hardware? Or leave it in core? Is Core PC specific, or deeper? // If we let hardware do it, we need to protect it from being used by System. // Probably belongs in hardware, and core is more specific stuff like CPU, memory, etc. //Core.PCI.OnPCIDeviceFound = PCIDeviceFound; //TODO: Since this is FCL, its "common". Otherwise it should be // system level and not accessible from Core. Need to think about this // for the future. Console.Clear(); Console.WriteLine("Finding PCI Devices"); mDebugger.Send("PCI Devices"); PCI.Setup(); Console.WriteLine("Starting ACPI"); mDebugger.Send("ACPI Init"); ACPI.Start(); // http://wiki.osdev.org/%228042%22_PS/2_Controller#Initialising_the_PS.2F2_Controller // TODO: USB should be initialized before the PS/2 controller // TODO: ACPI should be used to check if a PS/2 controller exists mDebugger.Send("PS/2 Controller Init"); if (InitPS2) { PS2Controller.Initialize(InitScrollWheel); } else { mDebugger.Send("PS/2 Controller disabled in User Kernel"); } if (IDEInit) { IDE.InitDriver(); } else { mDebugger.Send("IDE Driver disabled in User Kernel"); } AHCI.InitDriver(); //EHCI.InitDriver(); if (InitNetwork) { mDebugger.Send("Network Devices Init"); NetworkInit.Init(); } else { mDebugger.Send("Network Driver disabled in User Kernel"); } Console.WriteLine("Enabling Serial Output on COM1"); Serial.Enable(); mDebugger.Send("Done initializing Cosmos.HAL.Global"); } /// <summary> /// Enable interrupts. /// </summary> public static void EnableInterrupts() => CPU.EnableInterrupts(); /// <summary> /// Get keyboard devices. /// </summary> /// <returns>IEnumerable{KeyboardBase} value.</returns> public static IEnumerable<KeyboardBase> GetKeyboardDevices() { var xKeyboardDevices = new List<KeyboardBase>(); if (PS2Controller.FirstDevice is KeyboardBase xKeyboard1) { xKeyboardDevices.Add(xKeyboard1); } if (PS2Controller.SecondDevice is KeyboardBase xKeyboard2) { xKeyboardDevices.Add(xKeyboard2); } return xKeyboardDevices; } /// <summary> /// Get mouse devices. /// </summary> /// <returns>IEnumerable{MouseBase} value.</returns> public static IEnumerable<MouseBase> GetMouseDevices() { var xMouseDevices = new List<MouseBase>(); if (PS2Controller.FirstDevice is PS2Mouse xMouse1) { xMouseDevices.Add(xMouse1); } if (PS2Controller.SecondDevice is PS2Mouse xMouse2) { xMouseDevices.Add(xMouse2); } return xMouseDevices; } }
30.020134
108
0.610329
[ "BSD-3-Clause" ]
Kiirx/Cosmos
source/Cosmos.HAL2/Global.cs
4,473
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.GoogleNative.AccessContextManager.V1.Outputs { /// <summary> /// Specifies how APIs are allowed to communicate within the Service Perimeter. /// </summary> [OutputType] public sealed class VpcAccessibleServicesResponse { /// <summary> /// The list of APIs usable within the Service Perimeter. Must be empty unless 'enable_restriction' is True. You can specify a list of individual services, as well as include the 'RESTRICTED-SERVICES' value, which automatically includes all of the services protected by the perimeter. /// </summary> public readonly ImmutableArray<string> AllowedServices; /// <summary> /// Whether to restrict API calls within the Service Perimeter to the list of APIs specified in 'allowed_services'. /// </summary> public readonly bool EnableRestriction; [OutputConstructor] private VpcAccessibleServicesResponse( ImmutableArray<string> allowedServices, bool enableRestriction) { AllowedServices = allowedServices; EnableRestriction = enableRestriction; } } }
37.74359
292
0.693614
[ "Apache-2.0" ]
AaronFriel/pulumi-google-native
sdk/dotnet/AccessContextManager/V1/Outputs/VpcAccessibleServicesResponse.cs
1,472
C#
// (c) Copyright HutongGames, LLC 2010-2013. All rights reserved. using UnityEngine; namespace HutongGames.PlayMaker.Actions { [ActionCategory("Substance")] [Tooltip("Set a named float property in a Substance material. NOTE: Use Rebuild Textures after setting Substance properties.")] public class SetProceduralFloat : FsmStateAction { [RequiredField] [Tooltip("The Substance Material.")] public FsmMaterial substanceMaterial; [RequiredField] [Tooltip("The named float property in the material.")] public FsmString floatProperty; [RequiredField] [Tooltip("The value to set the property to.")] public FsmFloat floatValue; [Tooltip("NOTE: Updating procedural materials every frame can be very slow!")] public bool everyFrame; public override void Reset() { substanceMaterial = null; floatProperty = ""; floatValue = 0f; everyFrame = false; } public override void OnEnter() { DoSetProceduralFloat(); if (!everyFrame) { Finish(); } } public override void OnUpdate() { DoSetProceduralFloat(); } private void DoSetProceduralFloat() { #if !(UNITY_IPHONE || UNITY_IOS || UNITY_ANDROID || UNITY_NACL || UNITY_FLASH || UNITY_PS3 || UNITY_PS4 || UNITY_XBOXONE || UNITY_BLACKBERRY || UNITY_METRO || UNITY_WP8 || UNITY_WIIU || UNITY_PSM || UNITY_WEBGL) var substance = substanceMaterial.Value as ProceduralMaterial; if (substance == null) { LogError("The Material is not a Substance Material!"); return; } substance.SetProceduralFloat(floatProperty.Value, floatValue.Value); #endif } } }
25.515625
211
0.695652
[ "MIT" ]
BigBroken/sLord
Assets/PlayMaker/Actions/ProceduralMaterial/SetProceduralFloat.cs
1,633
C#
using System.IO; using Packager.Hash; using Packager.Models; using Packager.Transfers; namespace Packager { public class Run { private const string ProjectPath = "../../../../Wallon/bin/Debug"; // chemin du fichier à packager private readonly Config _config; public Run(string configPath) { _config = LoadConfig(configPath); SelectFiles(_config.ProjectPath, _config.TempPath); Compresser(_config.TempPath, _config.Archive.Path, _config.Archive.Name); Hash( Path.Combine(_config.Archive.Path, _config.Archive.Name), Path.Combine(_config.Hash.Path, _config.Hash.Name) ); // upload l'archive de la release Upload( Path.Combine(_config.Archive.Path, _config.Archive.Name), Path.Combine(_config.Server, _config.Archive.Name) ); // upload le fichier hash de la release Upload( Path.Combine(_config.Hash.Path, _config.Hash.Name), Path.Combine(_config.Server, _config.Hash.Name) ); //todo persist files (config.ini) } /** * <summary>Charge le fichier de configuration du packager</summary> * <param name="configPath">Chemin du fichier de config à charger</param> * <returns>Le modèle de configuration hydraté</returns> */ private Config LoadConfig(string configPath) { return Configuration.LoadConfig<Config>(Path.Combine(ProjectPath, "packager.json")); } /** * <summary>Sélectionne les fichiers à mettre dans l'archive</summary> * <param name="projectPath">Répertoire du projet à packager</param> * <param name="tempPath">Répertoire temporaire où travailler</param> */ private void SelectFiles(string projectPath, string tempPath) { Selecter selecter = new Selecter(); selecter.RemoveExtensions("pdb", "zip"); // exclu les fichiers avec ces extensions selecter.CopyFiles(projectPath, tempPath); // copie le contenu de ProjectPath dans TempPath } /** * <summary>Compresse les fichiers dans une nouvelle archive</summary> * <param name="tempPath">Répertoire temporaire où travailler</param> * <param name="archivePath">Répertoire de l'archive à générer</param> * <param name="archiveName">Nom de l'archive à générer</param> */ private void Compresser(string tempPath, string archivePath, string archiveName) { Compress.Zip(tempPath, Path.Combine(archivePath, archiveName)); // compresse le contenu de TempPath dans l'archive ArchivePath } /** * <summary>Upload un fichier</summary> * <param name="sourcePath">Chemin du fichier à uploader</param> * <param name="destinationPath">Chemin du fichier à créer sur le serveur distant</param> */ private void Upload(string sourcePath, string destinationPath) { // initialise le protocole IAuth upload = new Ftp() { User = "", Password = "", Source = sourcePath, Destination = destinationPath }; upload.Upload(); // upload le fichier } /** * <summary>Hash un fichier</summary> * <param name="source">Fichier à hasher</param> * <param name="destination">Chemin du fichier à hasher contenant le hash</param> */ //private void Hash(string archivePath, string archiveName, string hashPath, string hashName) private void Hash(string source, string destination) { // initialise le hasher Hasher hasher = new Hasher { FileName = source }; hasher.HashFile(); // hash le fichier hasher.SaveHash(destination); // sauvegarde le hash dans un fichier } } }
30.175439
129
0.704942
[ "MIT" ]
secretMoi/Wallon
Packager/Run.cs
3,466
C#
using System; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; namespace DotNetCoreSqlDb.Migrations { public partial class InitialCreate : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "Todo", columns: table => new { ID = table.Column<int>(nullable: false) .Annotation("Sqlite:Autoincrement", true) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), Description = table.Column<string>(nullable: true), CreatedDate = table.Column<DateTime>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Todo", x => x.ID); }); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "Todo"); } } }
33.705882
122
0.557592
[ "MIT" ]
ANKGITDEMOS/AppInsightsLogging
Migrations/20200423113402_InitialCreate.cs
1,148
C#
using MicroBootstrap.Abstractions.Persistence; namespace BuildingBlocks.IntegrationTests.Mock; public class NullDataSeeder : IDataSeeder { public Task SeedAllAsync() { return Task.CompletedTask; } }
18.416667
47
0.751131
[ "MIT" ]
BuiTanLan/ecommerce-microservices
tests/BuildingBlocks/BuildingBlocks.IntegrationTest/Mock/NullDataSeeder.cs
221
C#
using Hyperledger.Indy.DidApi; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Threading.Tasks; namespace Hyperledger.Indy.Test.SignusTests { [TestClass] public class StoreTheirDidTest : IndyIntegrationTestWithSingleWallet { private const string _verkey = "GjZWsBLgZCR18aL468JAT7w9CZRiBnpxUPPgyQxh4voa"; [TestMethod] public async Task TestStoreTheirDidWorks() { await Did.StoreTheirDidAsync(wallet, string.Format("{{\"did\":\"{0}\"}}", DID1)); } [TestMethod] public async Task TestCreateMyDidWorksForInvalidIdentityJson() { var ex = await Assert.ThrowsExceptionAsync<InvalidStructureException>(() => Did.StoreTheirDidAsync(wallet, "{\"field\":\"value\"}") ); } [TestMethod] public async Task TestStoreTheirDidWorksWithVerkey() { var json = string.Format(IDENTITY_JSON_TEMPLATE, DID1, _verkey); await Did.StoreTheirDidAsync(wallet, json); } [TestMethod] public async Task TestStoreTheirDidWorksWithoutDid() { var ex = await Assert.ThrowsExceptionAsync<InvalidStructureException>(() => Did.StoreTheirDidAsync(wallet, string.Format("{{\"verkey\":\"{0}\"}}", _verkey)) ); } } }
32.348837
96
0.616104
[ "Apache-2.0" ]
Diiaablo95/indy-sdk
wrappers/dotnet/indy-sdk-dotnet-test/DidTests/StoreTheirDidTest.cs
1,393
C#
/* * Copyright 2011-2015 Numeric Technology * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Reflection; using Castle.ActiveRecord; using KPAttributes; using KPGlobalization; namespace KPExtension { /// <summary> /// <para>Authors: Juliano Tiago Rinaldi and /// Tiago Antonio Jacobi</para> /// </summary> public static class KPTypeExtension { public static string GetEntityColumnNameDB(this Type type, string propertyEntity) { PropertyInfo property = type.GetProperty(propertyEntity); if (property != null) { PrimaryKeyAttribute[] attributeKey = property.GetCustomAttributes( typeof(PrimaryKeyAttribute), false) as PrimaryKeyAttribute[]; if (attributeKey != null && attributeKey.Length > 0) return attributeKey[0].Column; PropertyAttribute[] attributeProp = property.GetCustomAttributes( typeof(PropertyAttribute), false) as PropertyAttribute[]; if (attributeProp != null && attributeProp.Length > 0) return attributeProp[0].Column; } return null; } // Retornar a Propriedade PrimaryKey da Entity public static PropertyInfo GetEntityPrimaryKey(this Type type) { foreach (PropertyInfo property in type.GetProperties()) { PrimaryKeyAttribute[] attributeKey = property.GetCustomAttributes( typeof(PrimaryKeyAttribute), false) as PrimaryKeyAttribute[]; if (attributeKey != null && attributeKey.Length > 0) return property; } return null; } // Extensão tenso que vai até o pai tentando pegar o Método public static MethodInfo GetMethodInheritance(this Type type, string name, Type[] types) { MethodInfo methodFind = type.GetMethod(name, types); if (methodFind != null) return methodFind; else if (type.BaseType != null) return type.BaseType.GetMethodInheritance(name, types); else return null; } // Extensão tenso que vai até o pai tentando pegar a Propriedade public static PropertyInfo GetPropertyInheritance(this Type type, string name) { PropertyInfo propInfo = type.GetProperty(name); if (propInfo != null) return propInfo; else if (type.BaseType != null) return type.BaseType.GetPropertyInheritance(name); else return null; } // Extensão verifica se o Tipo implementa / herda da classe public static bool IsSubclassOfRawGeneric(this Type generic, Type toCheck) { while (toCheck != null && toCheck != typeof(object)) { var cur = toCheck.IsGenericType ? toCheck.GetGenericTypeDefinition() : toCheck; if (generic == cur) { return true; } toCheck = toCheck.BaseType; } return false; } // Extensão que busca um KPDisplayName para traduzir a título da propriedade public static string GetTranslate(this PropertyInfo propertyInfo) { KPDisplayName[] attributes = propertyInfo.GetCustomAttributes( typeof(KPDisplayName), false) as KPDisplayName[]; if (attributes != null && attributes.Length > 0) return KPGlobalizationLanguage.GetString(attributes[0].DisplayName); return propertyInfo.Name; } } }
38.98374
96
0.552659
[ "Apache-2.0" ]
NumericTechnology/Platanum.Net
KPCore/KPExtension/KPTypeExtension.cs
4,805
C#
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.md in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Security.Principal; using System.Threading.Tasks; namespace Microsoft.AspNet.SignalR { /// <summary> /// Represents a SignalR request /// </summary> public interface IRequest { /// <summary> /// Gets the url for this request. /// </summary> Uri Url { get; } /// <summary> /// Gets the querystring for this request. /// </summary> NameValueCollection QueryString { get; } /// <summary> /// Gets the headers for this request. /// </summary> NameValueCollection Headers { get; } /// <summary> /// Gets the form for this request. /// </summary> NameValueCollection Form { get; } /// <summary> /// Gets the cookies for this request. /// </summary> IDictionary<string, Cookie> Cookies { get; } /// <summary> /// Gets security information for the current HTTP request. /// </summary> IPrincipal User { get; } /// <summary> /// Gets state for the current HTTP request. /// </summary> IDictionary<string, object> Items { get; } } }
27.288462
132
0.575053
[ "Apache-2.0" ]
AlaShiban/SignalR
src/Microsoft.AspNet.SignalR.Core/IRequest.cs
1,421
C#
using System.Collections.Generic; using SIL.Machine.Annotations; using SIL.Machine.DataStructures; using SIL.Machine.FeatureModel; using SIL.Machine.Rules; namespace SIL.Machine.Morphology.HermitCrab.MorphologicalRules { /// <summary> /// This class represents a morphological rule which combines two words in to one word. /// </summary> public class CompoundingRule : HCRuleBase, IMorphologicalRule { private readonly List<CompoundingSubrule> _subrules; private readonly IDBearerSet<Feature> _obligatorySyntacticFeatures; public CompoundingRule() { MaxApplicationCount = 1; Blockable = true; HeadRequiredSyntacticFeatureStruct = FeatureStruct.New().Value; NonHeadRequiredSyntacticFeatureStruct = FeatureStruct.New().Value; OutSyntacticFeatureStruct = FeatureStruct.New().Value; _subrules = new List<CompoundingSubrule>(); _obligatorySyntacticFeatures = new IDBearerSet<Feature>(); } public IList<CompoundingSubrule> Subrules { get { return _subrules; } } public int MaxApplicationCount { get; set; } public bool Blockable { get; set; } public FeatureStruct HeadRequiredSyntacticFeatureStruct { get; set; } public FeatureStruct NonHeadRequiredSyntacticFeatureStruct { get; set; } public FeatureStruct OutSyntacticFeatureStruct { get; set; } public ICollection<Feature> ObligatorySyntacticFeatures { get { return _obligatorySyntacticFeatures; } } public Stratum Stratum { get; set; } public override IRule<Word, ShapeNode> CompileAnalysisRule(Morpher morpher) { return new AnalysisCompoundingRule(morpher, this); } public override IRule<Word, ShapeNode> CompileSynthesisRule(Morpher morpher) { return new SynthesisCompoundingRule(morpher, this); } } }
28.225806
88
0.768571
[ "MIT" ]
russellmorley/machine
src/SIL.Machine.Morphology.HermitCrab/MorphologicalRules/CompoundingRule.cs
1,750
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("VkHackaton.Import")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("EPAM Systems")] [assembly: AssemblyProduct("VkHackaton.Import")] [assembly: AssemblyCopyright("Copyright © EPAM Systems 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("e10600b7-a433-40be-8e60-8ccd012a3ec5")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.540541
84
0.751052
[ "MIT" ]
fde001/vkhackaton2017
VkHackaton.Import/Properties/AssemblyInfo.cs
1,429
C#
using GhostPanel.BackgroundServices; using GhostPanel.Communication.Query; using GhostPanel.Communication.Query.Steam; using GhostPanel.Core.Data; using GhostPanel.Core.Data.Model; using GhostPanel.Core.Management; using GhostPanel.Core.Providers; using MediatR; using Microsoft.Extensions.Logging; using Moq; using Xunit; namespace UnitTests.Core.Management { public class ServerStatServiceShould { private ILoggerFactory _logger; private Mock<IServerProcessManagerProvider> _mockProcManagerProvider; private Mock<IRepository> _mockRepo; private Mock<IGameQueryFactory> _mockGameQueryFact; private Mock<IQueryProtocol> _mockGameQuery; private Mock<IMediator> _mockMediator; public ServerStatServiceShould() { _logger = new LoggerFactory(); _mockProcManagerProvider = new Mock<IServerProcessManagerProvider>(); var mockProcManager = new Mock<IServerProcessManager>(); mockProcManager .Setup(pm => pm.IsRunning(1)) .Returns(false); _mockProcManagerProvider .Setup(pmp => pmp.GetProcessManagerProvider()) .Returns(mockProcManager.Object); _mockRepo = new Mock<IRepository>(); _mockRepo .Setup(r => r.Update(new GameServer())) .Returns((GameServer) null); _mockGameQueryFact = new Mock<IGameQueryFactory>(); _mockGameQuery = new Mock<IQueryProtocol>(); _mockGameQuery .Setup(gq => gq.GetServerInfoAsync()) .ReturnsAsync(GetSteamServerInfo()); _mockMediator = new Mock<IMediator>(); } [Fact] public async void ValidateUpdateQueryStats() { var gameServer = GetGameServer(); _mockGameQueryFact .Setup(gqf => gqf.GetQueryProtocol(gameServer)) .Returns(_mockGameQuery.Object); var statService = new ServerStatService(_logger, _mockProcManagerProvider.Object, _mockRepo.Object, _mockGameQueryFact.Object, _mockMediator.Object); var result = await statService.UpdateServerQueryStatsAsync(gameServer); } [Fact] public void CheckServerProcSetStopped() { var gameServer = GetGameServer(); var statService = new ServerStatService(_logger, _mockProcManagerProvider.Object, _mockRepo.Object, _mockGameQueryFact.Object, _mockMediator.Object); var result = statService.CheckServerProc(gameServer); Assert.Equal(ServerStatusStates.Stopped, result.GameServerCurrentStats.Status); } [Fact] public void CheckServerProcSetRunning() { var gameServer = GetGameServer(); gameServer.GameServerCurrentStats.Pid = 111; var statService = new ServerStatService(_logger, _mockProcManagerProvider.Object, _mockRepo.Object, _mockGameQueryFact.Object, _mockMediator.Object); var result = statService.CheckServerProc(gameServer); Assert.Equal(ServerStatusStates.Running, result.GameServerCurrentStats.Status); } private GameServer GetGameServer() { var gameServer = new GameServer(); gameServer.GameServerCurrentStats.Status = ServerStatusStates.Running; gameServer.GameServerCurrentStats = new GameServerCurrentStats(); gameServer.Game.GameProtocol = new GameProtocol() { FullTypeName = "GhostPanel.Rcon.Steam.SteamQueryProtocol" }; return gameServer; } private ServerInfoBase GetSteamServerInfo() { return new SteamServerInfo() { Name = "Test server", Bots = 2, Game = "CSGO", Map = "de_dust", MaxPlayers = 32, CurrentPlayers = 10 }; } } }
35.508772
161
0.62747
[ "Apache-2.0" ]
barrycarey/ghostpanel
src/UnitTests/Core/Management/ServerStatServiceShould.cs
4,050
C#
/* ======================================================================= Copyright 2017 Technische Universitaet Darmstadt, Fachgebiet fuer Stroemungsdynamik (chair of fluid dynamics) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using BoSSS.Platform.LinAlg; using ilPSP.Utils; using BoSSS.Platform; using System.Diagnostics; using BoSSS.Foundation.Quadrature; using System.Linq; using System.Collections.Generic; using ilPSP; using BoSSS.Foundation.Grid.Classic; using ilPSP.Tracing; namespace BoSSS.Foundation.Grid.RefElements { /// <summary> /// The cubic reference element, i.e. $` K^{\textrm{cube} } = ( -1,1 )^3 $`. /// </summary> public partial class Cube : RefElement { /// <summary> /// The encoding to identify all six faces of the cube. /// </summary> public enum Edge { /// <summary> /// edge between this cell the neighbour cell with \f$ x \f$--coordinates closer to negative infinity. /// </summary> Left = 0, /// <summary> /// edge between this cell the neighbour cell with \f$ x \f$--coordinates closer to positive infinity. /// </summary> Right = 1, /// <summary> /// edge between this cell the neighbour cell with \f$ y \f$--coordinates closer to positive infinity. /// </summary> Top = 2, /// <summary> /// edge between this cell the neighbour cell with \f$ y \f$--coordinates closer to negative infinity. /// </summary> Bottom = 3, /// <summary> /// edge between this cell the neighbour cell with \f$ z \f$--coordinates closer to positive infinity /// </summary> Front = 4, /// <summary> /// edge between this cell the neighbour cell with \f$ z \f$--coordinates closer to negative infinity /// </summary> Back = 5 } private static Cube instance = null; private static readonly object padlock = new object(); /// <summary> /// Access to the single, global instance. /// </summary> public static Cube Instance { get { lock(padlock) { if(instance == null) { instance = new Cube(); } return instance; } } } /// <summary> /// standard constructor /// </summary> private Cube() { using(new FuncTrace()) { // =============== // define vertices // =============== var _Vertices = new double[8, 3] { { -1, -1, -1 }, { 1, -1, -1 }, { -1, 1, -1 }, { -1, -1, 1 }, { 1, 1, -1 }, { 1, 1, 1 }, { 1, -1, 1 }, { -1, 1, 1 }}; this.m_Vertices = new NodeSet(this, 8, 3); this.m_Vertices.InitializeFrom(_Vertices); this.m_Vertices.LockForever(); m_NoOfFaces = 6; // ============ // edge simplex // ============ m_FaceRefElement = Square.Instance; // =================================== // define Quadrature nodes and weights // =================================== { int mem = 0; var qrTemp1D = QuadRuleResource.DecodeFromBase64( Resource.LineQuadRules_bin); foreach(var q in qrTemp1D) { m_1Drules.Add(q.Item1, (q.Item2, q.Item3)); } } // ================================== // define the orthonormal polynomials // ================================== DefinePolynomials(); } } SortedDictionary<int, (double[,] Nodes, double[] Weights)> m_1Drules = new SortedDictionary<int, (double[,] Nodes, double[] Weights)>(); SortedDictionary<int, QuadRule> m_3drules = new SortedDictionary<int, QuadRule>(); /// <summary> /// <see cref="RefElement.GetQuadratureRule"/> /// </summary> /// <remarks> /// The 3D-Rules occupy a significant amount of memory (about 200 MB), so we only create those that we need on the fly. /// </remarks> public override QuadRule GetQuadratureRule(int DesiredOrder) { if (DesiredOrder > HighestKnownOrder) { throw new ArgumentOutOfRangeException("no quadrature rule for desired order " + DesiredOrder + " available for simplex " + this.GetType().Name + ".", "DesiredOrder"); } QuadRule realQr; if(!m_3drules.TryGetValue(DesiredOrder, out realQr)) { int OrderOfPrecision = m_1Drules.Keys.Where(order => order >= DesiredOrder).Min(); if(!m_3drules.TryGetValue(OrderOfPrecision, out realQr)) { var _1Drule = m_1Drules[OrderOfPrecision]; int NN = _1Drule.Weights.GetLength(0); int D = this.SpatialDimension; realQr = QuadRule.CreateEmpty(this, NN * NN * NN, D); for(int i = 0; i < NN; i++) { for(int j = 0; j < NN; j++) { for(int k = 0; k < NN; k++) { realQr.Nodes[(i * NN + j) * NN + k, 0] = _1Drule.Nodes[k, 0]; realQr.Nodes[(i * NN + j) * NN + k, 1] = _1Drule.Nodes[j, 0]; realQr.Nodes[(i * NN + j) * NN + k, 2] = _1Drule.Nodes[i, 0]; realQr.Weights[(i * NN + j) * NN + k] = _1Drule.Weights[i] * _1Drule.Weights[j] * _1Drule.Weights[k]; } } } realQr.OrderOfPrecision = OrderOfPrecision; realQr.Nodes.LockForever(); realQr.Weights.LockForever(); m_3drules.Add(OrderOfPrecision, realQr); // the rule of order 'OrderOfPrecision' must also be used for order 'DesiredOrder' if(DesiredOrder != OrderOfPrecision) m_3drules.Add(DesiredOrder, realQr); } else { m_3drules.Add(DesiredOrder, realQr); } } return realQr; } /// <summary> /// <see cref="RefElement.HighestKnownOrder"/> /// </summary> override public int HighestKnownOrder { get { return m_1Drules.Keys.Max(); } } /// <summary> /// transforms some vertices (<paramref name="EdgeVertices"/>) from the local 2D-coordinate system of either /// the top, bottom, left, right, front or back edge (see <see cref="Edge"/>) to the local /// coordinate system of the cube; /// </summary> /// <param name="EdgeIndex">0, 1, 2, 3, 4 or 5; <see cref="Edge"/></param> /// <param name="EdgeVertices">input;</param> /// <param name="VolumeVertices">output;</param> public override void TransformFaceCoordinates(int EdgeIndex, MultidimensionalArray EdgeVertices, MultidimensionalArray VolumeVertices) { if (EdgeVertices.Dimension != 2) throw new ArgumentException("dimension of EdgeVertices must be 2.", "EdgeVertices"); if (VolumeVertices.Dimension != 2) throw new ArgumentException("dimension of VolumeVertices must be 2.", "VolumeVertices"); if (VolumeVertices.GetLength(1) != 3) throw new ArgumentException("wrong spatial dimension of output", "VolumeVertices"); if (EdgeVertices.GetLength(1) != 2) throw new ArgumentException("wrong spatial dimension of input", "EdgeVertices"); if (EdgeVertices.GetLength(0) != VolumeVertices.GetLength(0)) throw new ArgumentException("mismatch in number of vertices between input and output.", "EdgeVertices,VolumeVertices"); int L = EdgeVertices.GetLength(0); switch (EdgeIndex) { case (int)Edge.Front: for (int i = 0; i < L; i++) { VolumeVertices[i, 0] = EdgeVertices[i, 0]; VolumeVertices[i, 1] = EdgeVertices[i, 1]; VolumeVertices[i, 2] = 1.0; } break; case (int)Edge.Back: for (int i = 0; i < L; i++) { VolumeVertices[i, 0] = EdgeVertices[i, 0]; VolumeVertices[i, 1] = EdgeVertices[i, 1]; VolumeVertices[i, 2] = -1.0; } break; case (int)Edge.Left: for (int i = 0; i < L; i++) { VolumeVertices[i, 0] = -1.0; VolumeVertices[i, 1] = EdgeVertices[i, 1]; VolumeVertices[i, 2] = EdgeVertices[i, 0]; } break; case (int)Edge.Right: for (int i = 0; i < L; i++) { VolumeVertices[i, 0] = 1.0; VolumeVertices[i, 1] = EdgeVertices[i, 1]; VolumeVertices[i, 2] = EdgeVertices[i, 0]; } break; case (int)Edge.Top: for (int i = 0; i < L; i++) { VolumeVertices[i, 0] = EdgeVertices[i, 0]; VolumeVertices[i, 1] = 1.0; VolumeVertices[i, 2] = EdgeVertices[i, 1]; } break; case (int)Edge.Bottom: for (int i = 0; i < L; i++) { VolumeVertices[i, 0] = EdgeVertices[i, 0]; VolumeVertices[i, 1] = -1.0; VolumeVertices[i, 2] = EdgeVertices[i, 1]; } break; default: throw new ArgumentException("EdgeIndex out of range"); } } /// <summary> /// partitions this cube into 8 sub-cubes of equal size; /// </summary> /// <returns></returns> public override AffineTrafo[] GetSubdivision() { AffineTrafo[] ret = new AffineTrafo[8]; for (int i = 0; i < 8; i++) { ret[i] = new AffineTrafo(3); ret[i].Matrix = MultidimensionalArray.Create(3,3); ret[i].Matrix.AccEye(1.0); ret[i].Matrix.Scale(0.5); ret[i].Affine = Vertices.ExtractSubArrayShallow(i, -1).To1DArray(); BLAS.dscal(3, 0.5, ret[i].Affine, 1); } return ret; } /// <summary> /// tests whether <paramref name="pt"/> is within the convex hull of /// vertices or not; /// </summary> /// <param name="pt"></param> /// <param name="tolerance"></param> /// <returns></returns> public override bool IsWithin(double[] pt, double tolerance) { if (pt.Length != 3) throw new ArgumentException("wrong spatial dimension.", "pt"); if ((pt[0] < -1.0 - tolerance) || (pt[0] > 1.0 + tolerance) || (pt[1] < -1.0 - tolerance) || (pt[1] > 1.0 + tolerance) || (pt[2] < -1.0 - tolerance) || (pt[2] > 1.0 + tolerance)) return false; else return true; } /// <summary> /// see <see cref="RefElement.GetNodeSet(int,out MultidimensionalArray,out int[])"/> /// </summary> protected override void GetNodeSet(int px, out MultidimensionalArray Nodes, out int[] Type) { if (px < 2) throw new ArgumentOutOfRangeException("at least two nodes in each direction are required."); Nodes = MultidimensionalArray.Create(px * px * px, 3); Type = new int[Nodes.GetLength(0)]; var Nodes1D = GenericBlas.Linspace(-1, 1, px); int cnt = 0; for (int i = 0; i < px; i++) { int i_edge = (i == 0 || i == px - 1) ? 1 : 0; for (int j = 0; j < px; j++) { int j_edge = (j == 0 || j == px - 1) ? 1 : 0; for (int k = 0; k < px; k++) { int k_edge = (k == 0 || k == px - 1) ? 1 : 0; Nodes[cnt, 0] = Nodes1D[i]; Nodes[cnt, 1] = Nodes1D[j]; Nodes[cnt, 2] = Nodes1D[k]; Type[cnt] = i_edge + j_edge + k_edge; cnt++; } } } } /// <summary> /// <see cref="RefElement.GetInterpolationNodes_NonLin"/> /// </summary> override protected void GetInterpolationNodes_NonLin(CellType Type, out NodeSet InterpolationNodes, out PolynomialList InterpolationPolynomials, out int[] NodeType, out int[] EntityIndex) { switch (Type) { case CellType.Cube_8: { base.SelectNodalPolynomials(2, out InterpolationNodes, out InterpolationPolynomials, out NodeType, out EntityIndex); return; } case CellType.Cube_20: { //MultidimensionalArray _InterpolationNodes; //Polynomial[] _InterpolationPolynomials; //int[] _NodeType; //int[] _EntityIndex; base.SelectNodalPolynomials(3, out InterpolationNodes, out InterpolationPolynomials, out NodeType, out EntityIndex, NodeTypeFilter: new int[] { 0, 1 }, ModalBasisSelector: delegate(Polynomial p) { for (int i = 0; i < p.Coeff.Length; i++) { int p1 = p.Exponents[i, 0]; int p2 = p.Exponents[i, 1]; int p3 = p.Exponents[i, 2]; if (p1 > 2 || p2 > 2 || p3 > 2) return false; if (p1 == 2 && p2 == 2) return false; if (p2 == 2 && p3 == 2) return false; if (p1 == 2 && p3 == 2) return false; } return true; }); Debug.Assert(NodeType.Length == 20); //// should be 27 Nodes, so we have to drop seven: //// it will be the volume node in the center of the cell and all face nodes //int _K = _InterpolationNodes.GetLength(0); //Debug.Assert(_K == 27); //Debug.Assert(_NodeType[0] == 0 && _NodeType[1] == 1 && _NodeType[2] == 1 && _NodeType[3] == 1 && _NodeType[4] == 1 && _NodeType[5] == 1 && _NodeType[6] == 1, "first 7 nodes should be the volume node and 6 face nodes"); //int D = _InterpolationNodes.GetLength(1); //Debug.Assert(D == 3, "spatial dimension is expected to be 3."); //int K = 20; //int offset = _K - K; //InterpolationNodes = MultidimensionalArray.Create(K, D); //InterpolationNodes.Set(_InterpolationNodes.ExtractSubArrayShallow(new int[] { offset, 0 }, new int[] { _K - 1, D - 1 })); //InterpolationPolynomials = new Polynomial[K]; //Array.Copy(_InterpolationPolynomials, offset, InterpolationPolynomials, 0, K); //NodeType = new int[K]; //Array.Copy(_NodeType, offset, NodeType, 0, K); //EntityIndex = new int[K]; //Array.Copy(_EntityIndex, offset, EntityIndex, 0, K); return; } case CellType.Cube_27: { base.SelectNodalPolynomials(3, out InterpolationNodes, out InterpolationPolynomials, out NodeType, out EntityIndex); return; } case CellType.Cube_64: { base.SelectNodalPolynomials(4, out InterpolationNodes, out InterpolationPolynomials, out NodeType, out EntityIndex); return; } case CellType.Cube_125: { base.SelectNodalPolynomials(5, out InterpolationNodes, out InterpolationPolynomials, out NodeType, out EntityIndex); return; } case CellType.Cube_216: { base.SelectNodalPolynomials(6, out InterpolationNodes, out InterpolationPolynomials, out NodeType, out EntityIndex); return; } //case CellType.Cube_343: { // base.SelectNodalPolynomials(7, out InterpolationNodes, out InterpolationPolynomials, out NodeType, out EntityIndex); // return; // } //case CellType.Cube_512: { // base.SelectNodalPolynomials(8, out InterpolationNodes, out InterpolationPolynomials, out NodeType, out EntityIndex); // return; // } //case CellType.Cube_729: { // base.SelectNodalPolynomials(9, out InterpolationNodes, out InterpolationPolynomials, out NodeType, out EntityIndex); // return; // } //case CellType.Cube_1000: { // base.SelectNodalPolynomials(10, out InterpolationNodes, out InterpolationPolynomials, out NodeType, out EntityIndex); // return; // } default: throw new NotImplementedException(); } } /// <summary> /// <see cref="RefElement.GetForeignElementMapping"/> /// </summary> /// <param name="Type"></param> /// <param name="conv"></param> /// <returns></returns> public override int[] GetForeignElementMapping(CellType Type, RefElement.ExchangeFormats conv) { int[] permutationArray = new int[Vertices.GetLength(0)]; for (int i = 0; i < permutationArray.Length; i++) { permutationArray[i] = i; } if (conv == ExchangeFormats.Gmsh || conv == ExchangeFormats.CGNS) { SwitchNode(ref permutationArray[2], ref permutationArray[3]); SwitchNode(ref permutationArray[3], ref permutationArray[4]); SwitchNode(ref permutationArray[5], ref permutationArray[6]); return permutationArray; } return permutationArray; } /// <summary> /// <see cref="RefElement.GetForeignElementType"/> /// </summary> /// <param name="Type"></param> /// <param name="conv"></param> /// <param name="ForeignName"></param> /// <param name="ForeignTypeConstant"></param> public override void GetForeignElementType(CellType Type, RefElement.ExchangeFormats conv, out string ForeignName, out int ForeignTypeConstant) { ForeignName = "Hexagon"; ForeignTypeConstant = 0; if (conv == ExchangeFormats.Gmsh) { if (Type == CellType.Cube_Linear) { ForeignTypeConstant = 5; } else if (Type == CellType.Cube_27) { ForeignTypeConstant = 12; } else if (Type == CellType.Cube_20) { ForeignTypeConstant = 27; } else if (Type == CellType.Cube_64) { ForeignTypeConstant = 92; } else if (Type == CellType.Cube_125) { ForeignTypeConstant = 93; } else { throw new NotSupportedException("Wrong minor cell type"); } } else if (conv == ExchangeFormats.CGNS) { if (Type == 0) { ForeignTypeConstant = 17; } else if (Type == CellType.Cube_20) { ForeignTypeConstant = 18; } else if (Type == CellType.Cube_27) { ForeignTypeConstant = 19; } else { throw new NotSupportedException("Wrong minor cell type"); } } else if (conv == ExchangeFormats.GambitNeutral) { ForeignName = "Brick"; if (Type == CellType.Cube_Linear) { ForeignTypeConstant = 4; } else { throw new NotSupportedException("Wrong minor cell type"); } } else { throw new NotSupportedException("Wrong foreign convention type"); } } } }
43.503831
245
0.465586
[ "Apache-2.0" ]
FDYdarmstadt/BoSSS
src/L2-foundation/BoSSS.Foundation/Cube.cs
22,188
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Epinova.ElasticSearch.Core")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Epinova AS")] [assembly: AssemblyProduct("Epinova.ElasticSearch.Core")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: Guid("0818a108-083d-438b-9183-aef12733618f")] [assembly: AssemblyVersion("11.4.0.0")] [assembly: AssemblyFileVersion("11.4.0.0")] [assembly: InternalsVisibleTo("Epinova.ElasticSearch.Core.EPiServer")] [assembly: InternalsVisibleTo("Epinova.ElasticSearch.Core.EPiServer.Commerce")] [assembly: InternalsVisibleTo("Core.EPiServer.Tests")] [assembly: InternalsVisibleTo("Core.Tests")] [assembly: InternalsVisibleTo("TestData")] [assembly: InternalsVisibleTo("Epi11demo")] [assembly: InternalsVisibleTo("Integration.Tests")] [assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]
44.583333
79
0.791589
[ "MIT" ]
rholzner/Epinova.Elasticsearch
src/Epinova.ElasticSearch.Core/Properties/AssemblyInfo.cs
1,073
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Runtime.InteropServices.Tests.Common; using Xunit; namespace System.Runtime.InteropServices.Tests { public partial class ReleaseComObjectTests { [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsNanoServer))] [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Not approved COM object for app")] public void ReleaseComObject_ValidComObject_Success() { var comObject = new ComImportObject(); Assert.Equal(0, Marshal.ReleaseComObject(comObject)); } } }
37
102
0.733591
[ "MIT" ]
2E0PGS/corefx
src/System.Runtime.InteropServices/tests/System/Runtime/InteropServices/Marshal/ReleaseComObjectTests.Windows.cs
777
C#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.CodeFixes.HideBase; using Microsoft.CodeAnalysis.Diagnostics; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.HideBase { public class HideBaseTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (null, new HideBaseCodeFixProvider()); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddNew)] public async Task TestAddNewToProperty() { await TestInRegularAndScriptAsync( @"class Application { public static Application Current { get; } } class App : Application { [|public static App Current|] { get; set; } }", @"class Application { public static Application Current { get; } } class App : Application { public static new App Current { get; set; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddNew)] public async Task TestAddNewToMethod() { await TestInRegularAndScriptAsync( @"class Application { public static void Method() { } } class App : Application { [|public static void Method() { }|] }", @"class Application { public static void Method() { } } class App : Application { public static new void Method() { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddNew)] public async Task TestAddNewToMember() { await TestInRegularAndScriptAsync( @"class Application { public string Test; } class App : Application { [|public int Test;|] }", @"class Application { public string Test; } class App : Application { public new int Test; }"); } } }
21.628866
160
0.679218
[ "Apache-2.0" ]
ammogcoder/roslyn
src/EditorFeatures/CSharpTest/Diagnostics/HideBase/HideBaseTests.cs
2,098
C#
namespace Shopping.Aggregator.Models { public class BasketItemExtendedModel { public int Quantity { get; set; } public string Color { get; set; } public decimal Price { get; set; } public string ProductId { get; set; } public string ProductName { get; set; } //Product Related Additional Fields public string Category { get; set; } public string Summary { get; set; } public string Description { get; set; } public string ImageFile { get; set; } } }
26.388889
41
0.694737
[ "MIT" ]
FelipeAMendes/AspnetMicroservices
src/ApiGateways/Shopping.Aggregator/Models/BasketItemExtendedModel.cs
477
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace CivopApp { public partial class Site_Mobile { /// <summary> /// HeadContent control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.ContentPlaceHolder HeadContent; /// <summary> /// form1 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.HtmlControls.HtmlForm form1; /// <summary> /// FeaturedContent control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.ContentPlaceHolder FeaturedContent; /// <summary> /// MainContent control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.ContentPlaceHolder MainContent; } }
33.923077
87
0.523243
[ "Unlicense" ]
LubosBrat/civop-test
CivopApp/Site.Mobile.Master.designer.cs
1,764
C#
using System.Diagnostics.CodeAnalysis; [assembly: SuppressMessage("Sonar Code Smell", "S3966:Objects should not be disposed more than once", Justification = "We dispose only BCL objects and we trust how they implemented Dispose()")] [assembly: SuppressMessage("Major Code Smell", "S0125:Sections of code should not be commented out", Justification = "We only comment code as TODOs")] [assembly: SuppressMessage("Info Code Smell", "S1135:Track uses of \"TODO\" tags", Justification = "True TODOs")] [assembly: SuppressMessage("CodeQuality", "IDE0079:Remove unnecessary suppression", Justification = "Do not warn")]
88
193
0.769481
[ "Apache-2.0" ]
rjosborne/aggregator-cli
src/aggregator-ruleng/GlobalSuppressions.cs
618
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Linq.Expressions; using System.Reflection; using JetBrains.Annotations; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Metadata.Internal; using Microsoft.EntityFrameworkCore.Query.Internal; using Microsoft.EntityFrameworkCore.Utilities; using Remotion.Linq; using Remotion.Linq.Clauses; using Remotion.Linq.Clauses.Expressions; using Remotion.Linq.Clauses.ResultOperators; using Remotion.Linq.Parsing; namespace Microsoft.EntityFrameworkCore.Query.ExpressionVisitors.Internal { public class NavigationRewritingExpressionVisitor : RelinqExpressionVisitor { private readonly EntityQueryModelVisitor _queryModelVisitor; private readonly List<NavigationJoin> _navigationJoins = new List<NavigationJoin>(); private readonly NavigationRewritingQueryModelVisitor _navigationRewritingQueryModelVisitor; private readonly NavigationRewritingExpressionVisitor _parentvisitor; private QueryModel _queryModel; private class NavigationJoin { public static void RemoveNavigationJoin( ICollection<NavigationJoin> navigationJoins, NavigationJoin navigationJoin) { if (!navigationJoins.Remove(navigationJoin)) { foreach (var nj in navigationJoins) { nj.Remove(navigationJoin); } } } public NavigationJoin( IQuerySource querySource, INavigation navigation, JoinClause joinClause, IEnumerable<IBodyClause> additionalBodyClauses, bool optionalNavigationInChain, bool dependentToPrincipal, QuerySourceReferenceExpression querySourceReferenceExpression) : this( querySource, navigation, joinClause, null, additionalBodyClauses, optionalNavigationInChain, dependentToPrincipal, querySourceReferenceExpression) { } public NavigationJoin( IQuerySource querySource, INavigation navigation, GroupJoinClause groupJoinClause, IEnumerable<IBodyClause> additionalBodyClauses, bool optionalNavigationInChain, bool dependentToPrincipal, QuerySourceReferenceExpression querySourceReferenceExpression) : this( querySource, navigation, null, groupJoinClause, additionalBodyClauses, optionalNavigationInChain, dependentToPrincipal, querySourceReferenceExpression) { } private NavigationJoin( IQuerySource querySource, INavigation navigation, JoinClause joinClause, GroupJoinClause groupJoinClause, IEnumerable<IBodyClause> additionalBodyClauses, bool optionalNavigationInChain, bool dependentToPrincipal, QuerySourceReferenceExpression querySourceReferenceExpression) { QuerySource = querySource; Navigation = navigation; JoinClause = joinClause; GroupJoinClause = groupJoinClause; AdditionalBodyClauses = additionalBodyClauses; OptionalNavigationInChain = optionalNavigationInChain; DependentToPrincipal = dependentToPrincipal; QuerySourceReferenceExpression = querySourceReferenceExpression; } public IQuerySource QuerySource { get; } public INavigation Navigation { get; } public JoinClause JoinClause { get; } public GroupJoinClause GroupJoinClause { get; } public IEnumerable<IBodyClause> AdditionalBodyClauses { get; } public bool OptionalNavigationInChain { get; } public bool DependentToPrincipal { get; } public QuerySourceReferenceExpression QuerySourceReferenceExpression { get; } public readonly List<NavigationJoin> NavigationJoins = new List<NavigationJoin>(); public IEnumerable<NavigationJoin> Iterate() { yield return this; foreach (var navigationJoin in NavigationJoins.SelectMany(nj => nj.Iterate())) { yield return navigationJoin; } } private void Remove(NavigationJoin navigationJoin) => RemoveNavigationJoin(NavigationJoins, navigationJoin); } private IAsyncQueryProvider _entityQueryProvider; public NavigationRewritingExpressionVisitor([NotNull] EntityQueryModelVisitor queryModelVisitor) { Check.NotNull(queryModelVisitor, nameof(queryModelVisitor)); _queryModelVisitor = queryModelVisitor; _navigationRewritingQueryModelVisitor = new NavigationRewritingQueryModelVisitor(this, _queryModelVisitor); } private NavigationRewritingExpressionVisitor( EntityQueryModelVisitor queryModelVisitor, IAsyncQueryProvider entityQueryProvider, NavigationRewritingExpressionVisitor parentvisitor) : this(queryModelVisitor) { _entityQueryProvider = entityQueryProvider; _parentvisitor = parentvisitor; } public virtual void Rewrite([NotNull] QueryModel queryModel) { Check.NotNull(queryModel, nameof(queryModel)); _queryModel = queryModel; _navigationRewritingQueryModelVisitor.VisitQueryModel(_queryModel); foreach (var navigationJoin in _navigationJoins) { InsertNavigationJoin(navigationJoin); } } protected override Expression VisitUnary(UnaryExpression node) { var newOperand = Visit(node.Operand); return node.NodeType == ExpressionType.Convert && newOperand.Type == node.Type ? newOperand : node.Update(newOperand); } private void InsertNavigationJoin(NavigationJoin navigationJoin) { var insertionIndex = 0; var bodyClause = navigationJoin.QuerySource as IBodyClause; if (bodyClause != null) { insertionIndex = _queryModel.BodyClauses.IndexOf(bodyClause) + 1; } if (_queryModel.MainFromClause == navigationJoin.QuerySource || insertionIndex > 0 || _parentvisitor == null) { foreach (var nj in navigationJoin.Iterate()) { _queryModel.BodyClauses.Insert(insertionIndex++, nj.JoinClause ?? (IBodyClause)nj.GroupJoinClause); foreach (var additionalBodyClause in nj.AdditionalBodyClauses) { _queryModel.BodyClauses.Insert(insertionIndex++, additionalBodyClause); } } } else { _parentvisitor.InsertNavigationJoin(navigationJoin); } } protected override Expression VisitSubQuery(SubQueryExpression expression) { var navigationRewritingExpressionVisitor = CreateVisitorForSubQuery(); navigationRewritingExpressionVisitor.Rewrite(expression.QueryModel); return expression; } protected override Expression VisitConstant(ConstantExpression node) { if (_entityQueryProvider == null) { _entityQueryProvider = (node.Value as IQueryable)?.Provider as IAsyncQueryProvider; var parent = _parentvisitor; while (parent != null) { parent._entityQueryProvider = _entityQueryProvider; parent = parent._parentvisitor; } } return node; } protected override Expression VisitBinary(BinaryExpression node) { var newLeft = Visit(node.Left); var newRight = Visit(node.Right); if (newLeft == node.Left && newRight == node.Right) { return node; } var leftNavigationJoin = _navigationJoins .SelectMany(nj => nj.Iterate()) .FirstOrDefault(nj => ReferenceEquals(nj.QuerySourceReferenceExpression, newLeft)); var rightNavigationJoin = _navigationJoins .SelectMany(nj => nj.Iterate()) .FirstOrDefault(nj => ReferenceEquals(nj.QuerySourceReferenceExpression, newRight)); var leftJoin = leftNavigationJoin?.JoinClause ?? leftNavigationJoin?.GroupJoinClause?.JoinClause; var rightJoin = rightNavigationJoin?.JoinClause ?? rightNavigationJoin?.GroupJoinClause?.JoinClause; if (leftNavigationJoin != null && rightNavigationJoin != null) { if (leftNavigationJoin.DependentToPrincipal && rightNavigationJoin.DependentToPrincipal) { newLeft = leftJoin?.OuterKeySelector; newRight = rightJoin?.OuterKeySelector; NavigationJoin.RemoveNavigationJoin(_navigationJoins, leftNavigationJoin); NavigationJoin.RemoveNavigationJoin(_navigationJoins, rightNavigationJoin); } } else { if (leftNavigationJoin != null) { var constantExpression = newRight as ConstantExpression; if (constantExpression != null && constantExpression.Value == null) { if (leftNavigationJoin.DependentToPrincipal) { newLeft = leftJoin?.OuterKeySelector; NavigationJoin.RemoveNavigationJoin(_navigationJoins, leftNavigationJoin); if (newLeft != null && IsCompositeKey(newLeft.Type)) { newRight = CreateNullCompositeKey(newLeft); } } } else { newLeft = leftJoin?.InnerKeySelector; } } if (rightNavigationJoin != null) { var constantExpression = newLeft as ConstantExpression; if (constantExpression != null && constantExpression.Value == null) { if (rightNavigationJoin.DependentToPrincipal) { newRight = rightJoin?.OuterKeySelector; NavigationJoin.RemoveNavigationJoin(_navigationJoins, rightNavigationJoin); if (newRight != null && IsCompositeKey(newRight.Type)) { newLeft = CreateNullCompositeKey(newRight); } } } else { newRight = rightJoin?.InnerKeySelector; } } } if (node.NodeType != ExpressionType.ArrayIndex && newLeft != null && newRight != null && newLeft.Type != newRight.Type) { if (newLeft.Type.IsNullableType() && !newRight.Type.IsNullableType()) { newRight = Expression.Convert(newRight, newLeft.Type); } else if (!newLeft.Type.IsNullableType() && newRight.Type.IsNullableType()) { newLeft = Expression.Convert(newLeft, newRight.Type); } } return Expression.MakeBinary(node.NodeType, newLeft, newRight); } private static NewExpression CreateNullCompositeKey(Expression otherExpression) => Expression.New( CompositeKey.CompositeKeyCtor, Expression.NewArrayInit( typeof(object), Enumerable.Repeat( Expression.Constant(null), ((NewArrayExpression)((NewExpression)otherExpression).Arguments.Single()).Expressions.Count))); protected override Expression VisitMember(MemberExpression node) { Check.NotNull(node, nameof(node)); return _queryModelVisitor.BindNavigationPathPropertyExpression( node, (ps, qs) => { return RewriteNavigationProperties( ps.ToList(), qs, node.Expression, node.Member.Name, node.Type, e => Expression.MakeMemberAccess(e, node.Member)); }) ?? base.VisitMember(node); } protected override Expression VisitMethodCall(MethodCallExpression node) { Check.NotNull(node, nameof(node)); if (!EntityQueryModelVisitor.IsPropertyMethod(node.Method)) { base.VisitMethodCall(node); } return _queryModelVisitor.BindNavigationPathPropertyExpression( node, (ps, qs) => { return RewriteNavigationProperties( ps.ToList(), qs, node.Arguments[0], (string)(node.Arguments[1] as ConstantExpression).Value, node.Type, e => Expression.Call(node.Method, e, node.Arguments[1])); }) ?? base.VisitMethodCall(node); } private Expression RewriteNavigationProperties( List<IPropertyBase> properties, IQuerySource querySource, Expression declaringExpression, string propertyName, Type propertyType, Func<Expression, Expression> propertyCreator) { var navigations = properties.OfType<INavigation>().ToList(); if (navigations.Any()) { var outerQuerySourceReferenceExpression = new QuerySourceReferenceExpression(querySource); if (_navigationRewritingQueryModelVisitor.AdditionalFromClauseBeingProcessed != null && navigations.Last().IsCollection()) { return RewriteSelectManyNavigationsIntoJoins( outerQuerySourceReferenceExpression, navigations, _navigationRewritingQueryModelVisitor.AdditionalFromClauseBeingProcessed); } if (navigations.Count == 1 && navigations[0].IsDependentToPrincipal()) { var foreignKeyMemberAccess = CreateForeignKeyMemberAccess(propertyName, declaringExpression, navigations[0]); if (foreignKeyMemberAccess != null) { return foreignKeyMemberAccess; } } if (_navigationRewritingQueryModelVisitor.InsideInnerKeySelector) { var translated = CreateSubqueryForNavigations( outerQuerySourceReferenceExpression, navigations, propertyCreator); return translated; } var navigationResultExpression = RewriteNavigationsIntoJoins( outerQuerySourceReferenceExpression, navigations, properties.Count == navigations.Count ? null : propertyType, propertyCreator); return navigationResultExpression; } return default(Expression); } private static Expression CreateForeignKeyMemberAccess(string propertyName, Expression declaringExpression, INavigation navigation) { var principalKey = navigation.ForeignKey.PrincipalKey; if (principalKey.Properties.Count == 1) { Debug.Assert(navigation.ForeignKey.Properties.Count == 1); var principalKeyProperty = principalKey.Properties[0]; if (principalKeyProperty.Name == propertyName && principalKeyProperty.ClrType == navigation.ForeignKey.Properties[0].ClrType) { var declaringMethodCallExpression = declaringExpression as MethodCallExpression; var parentDeclaringExpression = declaringMethodCallExpression != null && EntityQueryModelVisitor.IsPropertyMethod(declaringMethodCallExpression.Method) ? declaringMethodCallExpression.Arguments[0] : (declaringExpression as MemberExpression)?.Expression; if (parentDeclaringExpression != null) { var foreignKeyPropertyExpression = CreateKeyAccessExpression(parentDeclaringExpression, navigation.ForeignKey.Properties); return foreignKeyPropertyExpression; } } } return null; } private Expression CreateSubqueryForNavigations( Expression outerQuerySourceReferenceExpression, ICollection<INavigation> navigations, Func<Expression, Expression> propertyCreator) { var firstNavigation = navigations.First(); var targetEntityType = firstNavigation.GetTargetType(); var mainFromClause = new MainFromClause( "subQuery", targetEntityType.ClrType, CreateEntityQueryable(targetEntityType)); var querySourceReference = new QuerySourceReferenceExpression(mainFromClause); var subQueryModel = new QueryModel(mainFromClause, new SelectClause(querySourceReference)); var leftKeyAccess = CreateKeyAccessExpression( querySourceReference, firstNavigation.IsDependentToPrincipal() ? firstNavigation.ForeignKey.PrincipalKey.Properties : firstNavigation.ForeignKey.Properties); var rightKeyAccess = CreateKeyAccessExpression( outerQuerySourceReferenceExpression, firstNavigation.IsDependentToPrincipal() ? firstNavigation.ForeignKey.Properties : firstNavigation.ForeignKey.PrincipalKey.Properties); subQueryModel.BodyClauses.Add( new WhereClause( CreateKeyComparisonExpression(leftKeyAccess, rightKeyAccess))); subQueryModel.ResultOperators.Add(new FirstResultOperator(returnDefaultWhenEmpty: true)); var selectClauseExpression = (Expression)querySourceReference; selectClauseExpression = navigations .Skip(1) .Aggregate( selectClauseExpression, (current, navigation) => Expression.Property(current, navigation.Name)); subQueryModel.SelectClause = new SelectClause(propertyCreator(selectClauseExpression)); if (navigations.Count > 1) { var subQueryVisitor = CreateVisitorForSubQuery(); subQueryVisitor.Rewrite(subQueryModel); } var subQuery = new SubQueryExpression(subQueryModel); return subQuery; } public virtual NavigationRewritingExpressionVisitor CreateVisitorForSubQuery() => new NavigationRewritingExpressionVisitor(_queryModelVisitor, _entityQueryProvider, this); private static BinaryExpression CreateKeyComparisonExpression(Expression leftExpression, Expression rightExpression) { if (leftExpression.Type != rightExpression.Type) { if (leftExpression.Type.IsNullableType()) { Debug.Assert(leftExpression.Type.UnwrapNullableType() == rightExpression.Type); rightExpression = Expression.Convert(rightExpression, leftExpression.Type); } else { Debug.Assert(rightExpression.Type.IsNullableType()); Debug.Assert(rightExpression.Type.UnwrapNullableType() == leftExpression.Type); leftExpression = Expression.Convert(leftExpression, rightExpression.Type); } } return Expression.Equal(leftExpression, rightExpression); } private Expression RewriteNavigationsIntoJoins( QuerySourceReferenceExpression outerQuerySourceReferenceExpression, IEnumerable<INavigation> navigations, Type propertyType, Func<Expression, Expression> propertyCreator) { var querySourceReferenceExpression = outerQuerySourceReferenceExpression; var navigationJoins = _navigationJoins; var optionalNavigationInChain = false; foreach (var navigation in navigations) { if (!navigation.ForeignKey.IsRequired) { optionalNavigationInChain = true; } var targetEntityType = navigation.GetTargetType(); if (navigation.IsCollection()) { _queryModel.MainFromClause.FromExpression = CreateEntityQueryable(targetEntityType); var innerQuerySourceReferenceExpression = new QuerySourceReferenceExpression(_queryModel.MainFromClause); var leftKeyAccess = CreateKeyAccessExpression( querySourceReferenceExpression, navigation.IsDependentToPrincipal() ? navigation.ForeignKey.Properties : navigation.ForeignKey.PrincipalKey.Properties); var rightKeyAccess = CreateKeyAccessExpression( innerQuerySourceReferenceExpression, navigation.IsDependentToPrincipal() ? navigation.ForeignKey.PrincipalKey.Properties : navigation.ForeignKey.Properties); _queryModel.BodyClauses.Add( new WhereClause( CreateKeyComparisonExpression(leftKeyAccess, rightKeyAccess))); return _queryModel.MainFromClause.FromExpression; } var navigationJoin = navigationJoins .FirstOrDefault(nj => nj.QuerySource == querySourceReferenceExpression.ReferencedQuerySource && nj.Navigation == navigation); if (navigationJoin == null) { QuerySourceReferenceExpression innerQuerySourceReferenceExpression; var joinClause = BuildJoinFromNavigation( querySourceReferenceExpression, navigation, targetEntityType, optionalNavigationInChain, out innerQuerySourceReferenceExpression); var additionalBodyClauses = new List<IBodyClause>(); if (optionalNavigationInChain || !navigation.ForeignKey.IsRequired) { var groupJoinClause = new GroupJoinClause( joinClause.ItemName + "_group", typeof(IEnumerable<>).MakeGenericType(targetEntityType.ClrType), joinClause); var groupReferenceExpression = new QuerySourceReferenceExpression(groupJoinClause); var defaultIfEmptyMainFromClause = new MainFromClause(joinClause.ItemName + "_groupItem", joinClause.ItemType, groupReferenceExpression); var newQuerySourceReferenceExpression = new QuerySourceReferenceExpression(defaultIfEmptyMainFromClause); var defaultIfEmptyQueryModel = new QueryModel( defaultIfEmptyMainFromClause, new SelectClause(newQuerySourceReferenceExpression)); defaultIfEmptyQueryModel.ResultOperators.Add(new DefaultIfEmptyResultOperator(null)); var defaultIfEmptySubquery = new SubQueryExpression(defaultIfEmptyQueryModel); var defaultIfEmptyAdditionalFromClause = new AdditionalFromClause(joinClause.ItemName, joinClause.ItemType, defaultIfEmptySubquery); additionalBodyClauses.Add(defaultIfEmptyAdditionalFromClause); navigationJoins.Add( navigationJoin = new NavigationJoin( querySourceReferenceExpression.ReferencedQuerySource, navigation, groupJoinClause, additionalBodyClauses, optionalNavigationInChain, navigation.IsDependentToPrincipal(), new QuerySourceReferenceExpression(defaultIfEmptyAdditionalFromClause))); } else { navigationJoins.Add( navigationJoin = new NavigationJoin( querySourceReferenceExpression.ReferencedQuerySource, navigation, joinClause, additionalBodyClauses, optionalNavigationInChain, navigation.IsDependentToPrincipal(), innerQuerySourceReferenceExpression)); } } querySourceReferenceExpression = navigationJoin.QuerySourceReferenceExpression; navigationJoins = navigationJoin.NavigationJoins; } if (propertyType == null) { return querySourceReferenceExpression; } if (optionalNavigationInChain) { Expression memberAccessExpression = propertyCreator(querySourceReferenceExpression); if (!propertyType.IsNullableType()) { memberAccessExpression = Expression.Convert(memberAccessExpression, propertyType.MakeNullable()); } var constantNullExpression = propertyType.IsNullableType() ? Expression.Constant(null, propertyType) : Expression.Constant(null, propertyType.MakeNullable()); return Expression.Condition( Expression.NotEqual( querySourceReferenceExpression, Expression.Constant(null, querySourceReferenceExpression.Type)), memberAccessExpression, constantNullExpression); } return propertyCreator(querySourceReferenceExpression); } private Expression RewriteSelectManyNavigationsIntoJoins( QuerySourceReferenceExpression outerQuerySourceReferenceExpression, IEnumerable<INavigation> navigations, AdditionalFromClause additionalFromClauseBeingProcessed) { var querySourceReferenceExpression = outerQuerySourceReferenceExpression; var additionalJoinIndex = _queryModel.BodyClauses.IndexOf(additionalFromClauseBeingProcessed); var joinClauses = new List<JoinClause>(); foreach (var navigation in navigations) { var targetEntityType = navigation.GetTargetType(); QuerySourceReferenceExpression innerQuerySourceReferenceExpression; var joinClause = BuildJoinFromNavigation( querySourceReferenceExpression, navigation, targetEntityType, false, out innerQuerySourceReferenceExpression); joinClauses.Add(joinClause); querySourceReferenceExpression = innerQuerySourceReferenceExpression; } _queryModel.BodyClauses.RemoveAt(additionalJoinIndex); for (var i = 0; i < joinClauses.Count; i++) { _queryModel.BodyClauses.Insert(additionalJoinIndex + i, joinClauses[i]); } var querySourceReplacingVisitor = new QuerySourceReplacingExpressionVisitor( additionalFromClauseBeingProcessed, querySourceReferenceExpression); var queryModelVisitor = new ExpressionTransformingQueryModelVisitor(querySourceReplacingVisitor); queryModelVisitor.VisitQueryModel(_queryModel); return querySourceReferenceExpression; } private class QuerySourceReplacingExpressionVisitor : RelinqExpressionVisitor { private readonly IQuerySource _querySourceToReplace; private readonly QuerySourceReferenceExpression _targetQuerySourceReferenceExpression; public QuerySourceReplacingExpressionVisitor( IQuerySource querySourceToReplace, QuerySourceReferenceExpression targetQuerySourceReferenceExpression) { _querySourceToReplace = querySourceToReplace; _targetQuerySourceReferenceExpression = targetQuerySourceReferenceExpression; } protected override Expression VisitQuerySourceReference(QuerySourceReferenceExpression expression) { if (expression.ReferencedQuerySource == _querySourceToReplace) { return _targetQuerySourceReferenceExpression; } return base.VisitQuerySourceReference(expression); } } private JoinClause BuildJoinFromNavigation( QuerySourceReferenceExpression querySourceReferenceExpression, INavigation navigation, IEntityType targetEntityType, bool addNullCheckToOuterKeySelector, out QuerySourceReferenceExpression innerQuerySourceReferenceExpression) { var outerKeySelector = CreateKeyAccessExpression( querySourceReferenceExpression, navigation.IsDependentToPrincipal() ? navigation.ForeignKey.Properties : navigation.ForeignKey.PrincipalKey.Properties, addNullCheck: addNullCheckToOuterKeySelector); var joinClause = new JoinClause( $"{querySourceReferenceExpression.ReferencedQuerySource.ItemName}.{navigation.Name}", targetEntityType.ClrType, CreateEntityQueryable(targetEntityType), outerKeySelector, Expression.Constant(null)); innerQuerySourceReferenceExpression = new QuerySourceReferenceExpression(joinClause); var innerKeySelector = CreateKeyAccessExpression( innerQuerySourceReferenceExpression, navigation.IsDependentToPrincipal() ? navigation.ForeignKey.PrincipalKey.Properties : navigation.ForeignKey.Properties); if (innerKeySelector.Type != joinClause.OuterKeySelector.Type) { if (innerKeySelector.Type.IsNullableType()) { joinClause.OuterKeySelector = Expression.Convert( joinClause.OuterKeySelector, innerKeySelector.Type); } else { innerKeySelector = Expression.Convert( innerKeySelector, joinClause.OuterKeySelector.Type); } } joinClause.InnerKeySelector = innerKeySelector; return joinClause; } private static Expression CreateKeyAccessExpression( Expression target, IReadOnlyList<IProperty> properties, bool addNullCheck = false) { return properties.Count == 1 ? CreatePropertyExpression(target, properties[0], addNullCheck) : Expression.New( CompositeKey.CompositeKeyCtor, Expression.NewArrayInit( typeof(object), properties .Select(p => Expression.Convert(CreatePropertyExpression(target, p, addNullCheck), typeof(object))) .Cast<Expression>() .ToArray())); } private static readonly MethodInfo _propertyMethodInfo = typeof(EF).GetTypeInfo().GetDeclaredMethod(nameof(Property)); private static Expression CreatePropertyExpression(Expression target, IProperty property, bool addNullCheck) { var propertyExpression = (Expression)Expression.Call( null, _propertyMethodInfo.MakeGenericMethod(property.ClrType), target, Expression.Constant(property.Name)); if (!addNullCheck) { return propertyExpression; } var constantNull = property.ClrType.IsNullableType() ? Expression.Constant(null, property.ClrType) : Expression.Constant(null, property.ClrType.MakeNullable()); if (!property.ClrType.IsNullableType()) { propertyExpression = Expression.Convert(propertyExpression, propertyExpression.Type.MakeNullable()); } return Expression.Condition( Expression.NotEqual( target, Expression.Constant(null, target.Type)), propertyExpression, constantNull); } private static bool IsCompositeKey([NotNull] Type type) { Check.NotNull(type, nameof(type)); return type == typeof(CompositeKey); } private ConstantExpression CreateEntityQueryable(IEntityType targetEntityType) => Expression.Constant( _createEntityQueryableMethod .MakeGenericMethod(targetEntityType.ClrType) .Invoke(null, new object[] { _entityQueryProvider })); private static readonly MethodInfo _createEntityQueryableMethod = typeof(NavigationRewritingExpressionVisitor) .GetTypeInfo().GetDeclaredMethod(nameof(_CreateEntityQueryable)); [UsedImplicitly] // ReSharper disable once InconsistentNaming private static EntityQueryable<TResult> _CreateEntityQueryable<TResult>(IAsyncQueryProvider entityQueryProvider) => new EntityQueryable<TResult>(entityQueryProvider); private class NavigationRewritingQueryModelVisitor : ExpressionTransformingQueryModelVisitor { private readonly SubqueryInjector _subqueryInjector; public bool InsideInnerKeySelector { get; private set; } public AdditionalFromClause AdditionalFromClauseBeingProcessed { get; private set; } public NavigationRewritingQueryModelVisitor(NavigationRewritingExpressionVisitor transformingVisitor, EntityQueryModelVisitor queryModelVisitor) : base(transformingVisitor) { _subqueryInjector = new SubqueryInjector(queryModelVisitor); } public override void VisitAdditionalFromClause(AdditionalFromClause fromClause, QueryModel queryModel, int index) { var oldAdditionalFromClause = AdditionalFromClauseBeingProcessed; AdditionalFromClauseBeingProcessed = fromClause; fromClause.TransformExpressions(TransformingVisitor.Visit); AdditionalFromClauseBeingProcessed = oldAdditionalFromClause; } public override void VisitJoinClause(JoinClause joinClause, QueryModel queryModel, int index) => VisitJoinClauseInternal(joinClause); public override void VisitJoinClause(JoinClause joinClause, QueryModel queryModel, GroupJoinClause groupJoinClause) => VisitJoinClauseInternal(joinClause); private void VisitJoinClauseInternal(JoinClause joinClause) { joinClause.InnerSequence = TransformingVisitor.Visit(joinClause.InnerSequence); joinClause.OuterKeySelector = TransformingVisitor.Visit(joinClause.OuterKeySelector); var oldInsideInnerKeySelector = InsideInnerKeySelector; InsideInnerKeySelector = true; joinClause.InnerKeySelector = TransformingVisitor.Visit(joinClause.InnerKeySelector); if (joinClause.OuterKeySelector.Type.IsNullableType() && !joinClause.InnerKeySelector.Type.IsNullableType()) { joinClause.InnerKeySelector = Expression.Convert(joinClause.InnerKeySelector, joinClause.InnerKeySelector.Type.MakeNullable()); } if (joinClause.InnerKeySelector.Type.IsNullableType() && !joinClause.OuterKeySelector.Type.IsNullableType()) { joinClause.OuterKeySelector = Expression.Convert(joinClause.OuterKeySelector, joinClause.OuterKeySelector.Type.MakeNullable()); } InsideInnerKeySelector = oldInsideInnerKeySelector; } public override void VisitSelectClause(SelectClause selectClause, QueryModel queryModel) { var newSelector = _subqueryInjector.Visit(selectClause.Selector); selectClause.Selector = newSelector; selectClause.TransformExpressions(TransformingVisitor.Visit); } private class SubqueryInjector : RelinqExpressionVisitor { private readonly EntityQueryModelVisitor _queryModelVisitor; public SubqueryInjector(EntityQueryModelVisitor queryModelVisitor) { _queryModelVisitor = queryModelVisitor; } protected override Expression VisitSubQuery(SubQueryExpression expression) => expression; protected override Expression VisitMember(MemberExpression node) { Check.NotNull(node, nameof(node)); return _queryModelVisitor.BindNavigationPathPropertyExpression( node, (properties, querySource) => { var navigations = properties.OfType<INavigation>().ToList(); var collectionNavigation = navigations.SingleOrDefault(n => n.IsCollection()); return collectionNavigation != null ? InjectSubquery(node, collectionNavigation) : default(Expression); }) ?? base.VisitMember(node); } private static Expression InjectSubquery(Expression expression, INavigation collectionNavigation) { var targetType = collectionNavigation.GetTargetType().ClrType; var mainFromClause = new MainFromClause(targetType.Name.Substring(0, 1).ToLower(), targetType, expression); var selector = new QuerySourceReferenceExpression(mainFromClause); var subqueryModel = new QueryModel(mainFromClause, new SelectClause(selector)); var subqueryExpression = new SubQueryExpression(subqueryModel); var resultCollectionType = collectionNavigation.GetCollectionAccessor().CollectionType; var result = Expression.Call( _materializeCollectionNavigationMethodInfo.MakeGenericMethod(targetType), Expression.Constant(collectionNavigation), subqueryExpression); return resultCollectionType.GetTypeInfo().IsGenericType && resultCollectionType.GetGenericTypeDefinition() == typeof(ICollection<>) ? (Expression)result : Expression.Convert(result, resultCollectionType); } private static readonly MethodInfo _materializeCollectionNavigationMethodInfo = typeof(SubqueryInjector).GetTypeInfo() .GetDeclaredMethod(nameof(MaterializeCollectionNavigation)); [UsedImplicitly] private static ICollection<TEntity> MaterializeCollectionNavigation<TEntity>(INavigation navigation, IEnumerable<object> elements) { var collection = navigation.GetCollectionAccessor().Create(elements); return (ICollection<TEntity>)collection; } } } } }
42.75808
161
0.571972
[ "Apache-2.0" ]
davidroth/EntityFrameworkCore
src/Microsoft.EntityFrameworkCore/Query/ExpressionVisitors/Internal/NavigationRewritingExpressionVisitor.cs
43,656
C#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.UnitTests; using Xunit; namespace Microsoft.ApiDesignGuidelines.Analyzers.UnitTests { public class MovePInvokesToNativeMethodsClassFixerTests : CodeFixTestBase { protected override DiagnosticAnalyzer GetBasicDiagnosticAnalyzer() { return new MovePInvokesToNativeMethodsClassAnalyzer(); } protected override DiagnosticAnalyzer GetCSharpDiagnosticAnalyzer() { return new MovePInvokesToNativeMethodsClassAnalyzer(); } protected override CodeFixProvider GetBasicCodeFixProvider() { return new BasicMovePInvokesToNativeMethodsClassFixer(); } protected override CodeFixProvider GetCSharpCodeFixProvider() { return new CSharpMovePInvokesToNativeMethodsClassFixer(); } } }
34.606061
160
0.7338
[ "Apache-2.0" ]
amcasey/roslyn-analyzers
src/Microsoft.ApiDesignGuidelines.Analyzers/UnitTests/MovePInvokesToNativeMethodsClassTests.Fixer.cs
1,142
C#
using System; using System.Runtime.Serialization; using Spark.Cqrs.Commanding; using Spark.Cqrs.Eventing; /* Copyright (c) 2015 Spark Software Ltd. * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace Spark.Cqrs.Domain { /// <summary> /// A uniquely identifiable <see cref="Object"/> within a given <see cref="Aggregate"/> root. /// </summary> public abstract class Entity : StateObject { internal static class Property { public const String Id = "id"; } /// <summary> /// The unique entity identifier. /// </summary> [DataMember(Name = Property.Id)] public Guid Id { get; internal set; } /// <summary> /// Initializes a new instance of <see cref="Entity"/>. /// </summary> protected Entity() { } /// <summary> /// Initializes a new instance of <see cref="Entity"/> with the specified <paramref name="id"/>. /// </summary> /// <param name="id">The unique entity identifier.</param> protected Entity(Guid id) { Verify.NotEqual(Guid.Empty, id, nameof(id)); Id = id; } /// <summary> /// Raises the specified event. /// </summary> /// <param name="e">The <see cref="Event"/> to be raised.</param> protected void Raise(Event e) { Verify.NotNull(e, nameof(e)); CommandContext.GetCurrent().Raise(e); } } }
38.257576
158
0.64198
[ "MIT" ]
cbaxter/infrastructure
src/Core/Cqrs/Domain/Entity.cs
2,527
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the sagemaker-2017-07-24.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.SageMaker.Model { /// <summary> /// This is the response object from the CreateFlowDefinition operation. /// </summary> public partial class CreateFlowDefinitionResponse : AmazonWebServiceResponse { private string _flowDefinitionArn; /// <summary> /// Gets and sets the property FlowDefinitionArn. /// <para> /// The Amazon Resource Name (ARN) of the flow definition you create. /// </para> /// </summary> [AWSProperty(Required=true, Max=1024)] public string FlowDefinitionArn { get { return this._flowDefinitionArn; } set { this._flowDefinitionArn = value; } } // Check to see if FlowDefinitionArn property is set internal bool IsSetFlowDefinitionArn() { return this._flowDefinitionArn != null; } } }
30.775862
107
0.673389
[ "Apache-2.0" ]
ChristopherButtars/aws-sdk-net
sdk/src/Services/SageMaker/Generated/Model/CreateFlowDefinitionResponse.cs
1,785
C#
namespace AngleSharp.Core.Tests.Library { using AngleSharp; using AngleSharp.Dom.Css; using AngleSharp.Parser.Css; using NUnit.Framework; using System; [TestFixture] public class OptimizationPoolTests { [Test] public void RecycleStringBuilderReused() { var str = "Test"; var sb1 = Pool.NewStringBuilder(); sb1.Append(str); Assert.AreEqual(str, sb1.ToString()); var sb2 = Pool.NewStringBuilder(); Assert.AreEqual(String.Empty, sb2.ToString()); Assert.AreNotSame(sb1, sb2); sb1.ToPool(); sb2.ToPool(); } [Test] public void RecycleStringBuilderGetString() { var str = "Test"; var sb1 = Pool.NewStringBuilder(); sb1.Append(str); Assert.AreEqual(str, sb1.ToPool()); var sb2 = Pool.NewStringBuilder(); Assert.AreEqual(String.Empty, sb2.ToPool()); Assert.AreSame(sb1, sb2); } [Test] public void RecycleStringBuilderGetStringReturned() { var str = "Test"; var sb1 = Pool.NewStringBuilder(); sb1.Append(str); Assert.AreEqual(str, sb1.ToPool()); var sb2 = Pool.NewStringBuilder(); Assert.AreSame(sb1, sb2); sb2.Append(str); Assert.AreEqual(str, sb2.ToString()); var sb3 = Pool.NewStringBuilder(); Assert.AreNotEqual(sb1, sb3); Assert.AreEqual(String.Empty, sb3.ToPool()); sb2.ToPool(); } [Test] public void RecycleSelectorConstructorReused() { var sc1 = Pool.NewSelectorConstructor(); Assert.AreEqual(SimpleSelector.All, sc1.GetResult()); var sc2 = Pool.NewSelectorConstructor(); Assert.AreEqual(SimpleSelector.All, sc2.GetResult()); Assert.AreNotEqual(sc1, sc2); sc1.ToPool(); sc2.ToPool(); } [Test] public void RecycleSelectorConstructorBuild() { var divIdent = new CssKeywordToken(CssTokenType.Ident, "div", new TextPosition()); var sc1 = Pool.NewSelectorConstructor(); sc1.Apply(divIdent); Assert.AreNotEqual(SimpleSelector.All, sc1.ToPool()); var sc2 = Pool.NewSelectorConstructor(); Assert.AreEqual(SimpleSelector.All, sc2.ToPool()); Assert.AreSame(sc1, sc2); } } }
32.1
94
0.549844
[ "MIT" ]
Livven/AngleSharp
AngleSharp.Core.Tests/Library/OptimizationPool.cs
2,570
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the route53resolver-2018-04-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.Route53Resolver.Model { /// <summary> /// Container for the parameters to the AssociateResolverEndpointIpAddress operation. /// Adds IP addresses to an inbound or an outbound resolver endpoint. If you want to adding /// more than one IP address, submit one <code>AssociateResolverEndpointIpAddress</code> /// request for each IP address. /// /// /// <para> /// To remove an IP address from an endpoint, see <a>DisassociateResolverEndpointIpAddress</a>. /// </para> /// </summary> public partial class AssociateResolverEndpointIpAddressRequest : AmazonRoute53ResolverRequest { private IpAddressUpdate _ipAddress; private string _resolverEndpointId; /// <summary> /// Gets and sets the property IpAddress. /// <para> /// Either the IPv4 address that you want to add to a resolver endpoint or a subnet ID. /// If you specify a subnet ID, Resolver chooses an IP address for you from the available /// IPs in the specified subnet. /// </para> /// </summary> public IpAddressUpdate IpAddress { get { return this._ipAddress; } set { this._ipAddress = value; } } // Check to see if IpAddress property is set internal bool IsSetIpAddress() { return this._ipAddress != null; } /// <summary> /// Gets and sets the property ResolverEndpointId. /// <para> /// The ID of the resolver endpoint that you want to associate IP addresses with. /// </para> /// </summary> public string ResolverEndpointId { get { return this._resolverEndpointId; } set { this._resolverEndpointId = value; } } // Check to see if ResolverEndpointId property is set internal bool IsSetResolverEndpointId() { return this._resolverEndpointId != null; } } }
34
113
0.649827
[ "Apache-2.0" ]
Bio2hazard/aws-sdk-net
sdk/src/Services/Route53Resolver/Generated/Model/AssociateResolverEndpointIpAddressRequest.cs
2,890
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO.Ports; namespace Dribble_O_Mat_2._1 { public class SerialSettings { public List<string> SerialPorts { get; private set; } public string SerialPort { get; set; } public int Baud { get; set; } = 250000; public SerialSettings() { LoadSerialPorts(); } public void LoadSerialPorts() { SerialPorts = System.IO.Ports.SerialPort.GetPortNames().ToList(); } } }
22.074074
77
0.619128
[ "Unlicense" ]
Manfe07/Dribble_o_Mat
Monitor-Software/Dribble_O_Mat_2.1/SerialSettings.cs
598
C#
using Microsoft.EntityFrameworkCore; namespace Tests { public class InMemoryDbContext : NerdyMishka.EfCore.Identity.IdentityDbContext { public InMemoryDbContext(DbContextOptions options) : base(options) { } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { //optionsBuilder.UseInMemoryDatabase("Identity_Memory_Test"); base.OnConfiguring(optionsBuilder); } } }
25.421053
85
0.681159
[ "Apache-2.0" ]
nerdymishka/gainz
dotnet/test/Extensions/Identity.Tests/InMemoryDbContext.cs
483
C#
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.Aws.AppConfig { /// <summary> /// Provides an AppConfig Application resource. /// /// ## Example Usage /// /// ```csharp /// using Pulumi; /// using Aws = Pulumi.Aws; /// /// class MyStack : Stack /// { /// public MyStack() /// { /// var example = new Aws.AppConfig.Application("example", new Aws.AppConfig.ApplicationArgs /// { /// Description = "Example AppConfig Application", /// Tags = /// { /// { "Type", "AppConfig Application" }, /// }, /// }); /// } /// /// } /// ``` /// /// ## Import /// /// AppConfig Applications can be imported using their application ID, e.g., /// /// ```sh /// $ pulumi import aws:appconfig/application:Application example 71rxuzt /// ``` /// </summary> [AwsResourceType("aws:appconfig/application:Application")] public partial class Application : Pulumi.CustomResource { /// <summary> /// The Amazon Resource Name (ARN) of the AppConfig Application. /// </summary> [Output("arn")] public Output<string> Arn { get; private set; } = null!; /// <summary> /// The description of the application. Can be at most 1024 characters. /// </summary> [Output("description")] public Output<string?> Description { get; private set; } = null!; /// <summary> /// The name for the application. Must be between 1 and 64 characters in length. /// </summary> [Output("name")] public Output<string> Name { get; private set; } = null!; /// <summary> /// A map of tags to assign to the resource. If configured with a provider `default_tags` configuration block present, tags with matching keys will overwrite those defined at the provider-level. /// </summary> [Output("tags")] public Output<ImmutableDictionary<string, string>?> Tags { get; private set; } = null!; /// <summary> /// A map of tags assigned to the resource, including those inherited from the provider `default_tags` configuration block. /// </summary> [Output("tagsAll")] public Output<ImmutableDictionary<string, string>> TagsAll { get; private set; } = null!; /// <summary> /// Create a Application resource with the given unique name, arguments, and options. /// </summary> /// /// <param name="name">The unique name of the resource</param> /// <param name="args">The arguments used to populate this resource's properties</param> /// <param name="options">A bag of options that control this resource's behavior</param> public Application(string name, ApplicationArgs? args = null, CustomResourceOptions? options = null) : base("aws:appconfig/application:Application", name, args ?? new ApplicationArgs(), MakeResourceOptions(options, "")) { } private Application(string name, Input<string> id, ApplicationState? state = null, CustomResourceOptions? options = null) : base("aws:appconfig/application:Application", name, state, MakeResourceOptions(options, id)) { } private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id) { var defaultOptions = new CustomResourceOptions { Version = Utilities.Version, }; var merged = CustomResourceOptions.Merge(defaultOptions, options); // Override the ID if one was specified for consistency with other language SDKs. merged.Id = id ?? merged.Id; return merged; } /// <summary> /// Get an existing Application resource's state with the given name, ID, and optional extra /// properties used to qualify the lookup. /// </summary> /// /// <param name="name">The unique name of the resulting resource.</param> /// <param name="id">The unique provider ID of the resource to lookup.</param> /// <param name="state">Any extra arguments used during the lookup.</param> /// <param name="options">A bag of options that control this resource's behavior</param> public static Application Get(string name, Input<string> id, ApplicationState? state = null, CustomResourceOptions? options = null) { return new Application(name, id, state, options); } } public sealed class ApplicationArgs : Pulumi.ResourceArgs { /// <summary> /// The description of the application. Can be at most 1024 characters. /// </summary> [Input("description")] public Input<string>? Description { get; set; } /// <summary> /// The name for the application. Must be between 1 and 64 characters in length. /// </summary> [Input("name")] public Input<string>? Name { get; set; } [Input("tags")] private InputMap<string>? _tags; /// <summary> /// A map of tags to assign to the resource. If configured with a provider `default_tags` configuration block present, tags with matching keys will overwrite those defined at the provider-level. /// </summary> public InputMap<string> Tags { get => _tags ?? (_tags = new InputMap<string>()); set => _tags = value; } public ApplicationArgs() { } } public sealed class ApplicationState : Pulumi.ResourceArgs { /// <summary> /// The Amazon Resource Name (ARN) of the AppConfig Application. /// </summary> [Input("arn")] public Input<string>? Arn { get; set; } /// <summary> /// The description of the application. Can be at most 1024 characters. /// </summary> [Input("description")] public Input<string>? Description { get; set; } /// <summary> /// The name for the application. Must be between 1 and 64 characters in length. /// </summary> [Input("name")] public Input<string>? Name { get; set; } [Input("tags")] private InputMap<string>? _tags; /// <summary> /// A map of tags to assign to the resource. If configured with a provider `default_tags` configuration block present, tags with matching keys will overwrite those defined at the provider-level. /// </summary> public InputMap<string> Tags { get => _tags ?? (_tags = new InputMap<string>()); set => _tags = value; } [Input("tagsAll")] private InputMap<string>? _tagsAll; /// <summary> /// A map of tags assigned to the resource, including those inherited from the provider `default_tags` configuration block. /// </summary> public InputMap<string> TagsAll { get => _tagsAll ?? (_tagsAll = new InputMap<string>()); set => _tagsAll = value; } public ApplicationState() { } } }
37.487685
202
0.583574
[ "ECL-2.0", "Apache-2.0" ]
RafalSumislawski/pulumi-aws
sdk/dotnet/AppConfig/Application.cs
7,610
C#
using Handlebars.Core.Compiler.Structure; namespace Handlebars.Core.Compiler.Translation.Expressions { internal class CommentVisitor : HandlebarsExpressionVisitor { public static System.Linq.Expressions.Expression Visit(System.Linq.Expressions.Expression expr, CompilationContext compilationContext) { return new CommentVisitor(compilationContext).Visit(expr); } private CommentVisitor(CompilationContext compilationContext) : base(compilationContext) { } protected override System.Linq.Expressions.Expression VisitStatementExpression(StatementExpression sex) { if (sex.Body is CommentExpression) { return System.Linq.Expressions.Expression.Empty(); } return sex; } } }
31.37037
142
0.66588
[ "MIT" ]
esskar/Handlebars
source/Handlebars.Core/Compiler/Translation/Expressions/CommentVisitor.cs
849
C#
using AlgoRay_Projector.Interfaces; using System; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; namespace AlgoRay_Projector.ProjectorFunctionality { internal class CoreProjector : ICoreProjector { public async Task<Stopwatch> ProjectTest(Action testMethod, int millisecondsTimeout) { var stopwatch = new Stopwatch(); stopwatch.Start(); using (var cancellationTokenSource = new CancellationTokenSource(millisecondsTimeout)) { var newTask = new Task(() => { testMethod.Invoke(); }, cancellationTokenSource.Token); await TryTimeOutTaskAsync(newTask, cancellationTokenSource); } stopwatch.Stop(); return stopwatch; } private async Task TryTimeOutTaskAsync(Task task, CancellationTokenSource cancel) { task.Start(); while (!task.IsCompleted) { if (cancel.IsCancellationRequested) { throw new TimeoutException("Test timed out and took too long to complete!"); } } await task; } } }
26.895833
98
0.564679
[ "MIT" ]
ValentinShikovIT/AlgoRay
src/AlgoRay_Projector/ProjectorFunctionality/CoreProjector.cs
1,293
C#
/**************************************************************************** * Copyright (c) 2017 liangxie * * http://qframework.io * https://github.com/liangxiegame/QFramework * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. ****************************************************************************/ namespace QFramework { public class RemoveRetainAudioMsg : QMsg { public string AudioName; public RemoveRetainAudioMsg(string audioName) : base((int) AudioEvent.RemoveRetainAudioAudio) { AudioName = audioName; } } }
42.432432
95
0.683439
[ "MIT" ]
317392507/QFramework
Assets/QFramework/Framework/1.ResKit/2.Audio/Msg/RemoteRetainAudioMsg.cs
1,570
C#
using MediatR; using NetPad.Sessions; namespace NetPad.CQs; public class ActivateScriptCommand : Command { public ActivateScriptCommand(Guid scriptId) { ScriptId = scriptId; } public Guid ScriptId { get; } public class Handler : IRequestHandler<ActivateScriptCommand> { private readonly ISession _session; public Handler(ISession session) { _session = session; } public async Task<Unit> Handle(ActivateScriptCommand request, CancellationToken cancellationToken) { await _session.ActivateAsync(request.ScriptId); return Unit.Value;; } } }
21.677419
106
0.647321
[ "MIT" ]
tareqimbasher/NetPad
src/Core/NetPad.Application/CQs/ActivateScriptCommand.cs
672
C#
using System; using Magnum.Pipeline; using Magnum.Pipeline.Segments; using pjsip4net.Core.Interfaces; namespace pjsip4net.Core { public class EventsProvider : IEventsProvider { private readonly Pipe _eventsPipe; private readonly ISubscriptionScope _scope; public EventsProvider() { _eventsPipe = PipeSegment.Input(PipeSegment.End());; _scope = _eventsPipe.NewSubscriptionScope(); } #region Implementation of IEventsProvider public void Publish<T>(T @event) where T : class { _eventsPipe.Send(@event); } public void Subscribe<T>(Action<T> actOnEvent) where T : class { _scope.Subscribe(new DelegatingConsumer<T>(actOnEvent)); } public IDisposable SubscribeTemporarilly<T>(Action<T> actOnEvent) where T : class { var result = _eventsPipe.NewSubscriptionScope(); result.Subscribe(new DelegatingConsumer<T>(actOnEvent)); return result; } #endregion } }
26.975
89
0.626506
[ "Apache-2.0" ]
moljac/pjsip4net
pjsip4net.Core/EventsProvider.cs
1,079
C#
using System; using System.Collections.Generic; public class AchievementIdComparer : global::System.Collections.Generic.IEqualityComparer<global::AchievementId> { public bool Equals(global::AchievementId x, global::AchievementId y) { return x == y; } public int GetHashCode(global::AchievementId obj) { return (int)obj; } public static readonly global::AchievementIdComparer Instance = new global::AchievementIdComparer(); }
24.444444
112
0.775
[ "CC0-1.0" ]
FreyaFreed/mordheim
Assembly-CSharp/AchievementIdComparer.cs
442
C#
using PearlCalculatorLib.PearlCalculationLib.MathLib; using PearlCalculatorLib.PearlCalculationLib.World; using PearlCalculatorLib.PearlCalculationLib.AABB; using System; using System.Collections.Generic; using System.Text; namespace PearlCalculatorLib.PearlCalculationLib.Entity { [Serializable] public class PearlEntity : Entity , ICloneable { public override Space3D Size => new Space3D(0.25, 0.25, 0.25); public PearlEntity(Space3D momemtum, Space3D position) { this.Motion = momemtum; this.Position = position; } public PearlEntity(PearlEntity pearl) : this(pearl.Motion , pearl.Position) { } public PearlEntity() { } public PearlEntity WithPosition(double x , double y , double z) { this.Position = new Space3D(x , y , z); return this; } public PearlEntity WithVector(double x , double y , double z) { this.Motion = new Space3D(x , y , z); return this; } public override void Tick() { Position += Motion; Motion *= 0.99; Motion.Y -= 0.03; } public object Clone() { PearlEntity pearl = new PearlEntity { Position = this.Position, Motion = this.Motion }; return pearl; } } }
25.473684
87
0.565427
[ "MIT" ]
Colton-Ko/PearlCalculatorCore
PearlCalculatorLib/PearlCalculationLib/Entity/PearlEntity.cs
1,454
C#
#pragma checksum "C:\Users\Filip Vrba\Documents\GitHub\InfnetFV-Core\InfnetFV-Core\Pages\_ViewStart.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "7091c65830b0329e613be026ede8a57552863778" // <auto-generated/> #pragma warning disable 1591 [assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(InfnetFV_Core.Pages.Pages__ViewStart), @"mvc.1.0.view", @"/Pages/_ViewStart.cshtml")] [assembly:global::Microsoft.AspNetCore.Mvc.Razor.Compilation.RazorViewAttribute(@"/Pages/_ViewStart.cshtml", typeof(InfnetFV_Core.Pages.Pages__ViewStart))] namespace InfnetFV_Core.Pages { #line hidden using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.AspNetCore.Mvc.ViewFeatures; #line 1 "C:\Users\Filip Vrba\Documents\GitHub\InfnetFV-Core\InfnetFV-Core\Pages\_ViewImports.cshtml" using InfnetFV_Core; #line default #line hidden [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"7091c65830b0329e613be026ede8a57552863778", @"/Pages/_ViewStart.cshtml")] [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"3242a00c4945873b1ed9a28a405569a3e2469a66", @"/Pages/_ViewImports.cshtml")] public class Pages__ViewStart : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage<dynamic> { #pragma warning disable 1998 public async override global::System.Threading.Tasks.Task ExecuteAsync() { #line 1 "C:\Users\Filip Vrba\Documents\GitHub\InfnetFV-Core\InfnetFV-Core\Pages\_ViewStart.cshtml" Layout = "_Layout"; #line default #line hidden } #pragma warning restore 1998 [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper<dynamic> Html { get; private set; } } } #pragma warning restore 1591
55.530612
191
0.768467
[ "MIT" ]
filipvrba/InfnetFV-Core
InfnetFV-Core/obj/Debug/netcoreapp2.2/Razor/Pages/_ViewStart.g.cshtml.cs
2,721
C#
using UnityEngine; using System; public class DoorProxy:MonoBehaviour { public int doorIndex = 0; public bool alwaysLock = false; public bool neverLock = false; public int maxDoorAngle = 150; public GameObject partnerDoor; }
15.8
36
0.755274
[ "MIT" ]
DancingEngie/IntruderMafia
Assets/IntruderMM/Scripts/DoorProxy.cs
237
C#
using System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Reflection; using Mono.Cecil.Cil; using MonoMod.Utils; namespace R2API.Utils { public static class Reflection { private const BindingFlags AllFlags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly; private delegate T GetDelegate<out T>(object instance); private delegate void SetDelegate<in T>(object instance, T value); //private delegate object CallDelegate(object instance, object[] arguments); private delegate void SetDelegateRef<TInstance, in TValue>(ref TInstance instance, TValue value) where TInstance : struct; private delegate T GetDelegateRef<TInstance, out T>(ref TInstance instance) where TInstance : struct; #region Caches // Field private static readonly ConcurrentDictionary<(Type T, string name), FieldInfo> FieldCache = new ConcurrentDictionary<(Type T, string name), FieldInfo>(); private static readonly ConcurrentDictionary<FieldInfo, Delegate> FieldGetDelegateCache = new ConcurrentDictionary<FieldInfo, Delegate>(); private static readonly ConcurrentDictionary<FieldInfo, Delegate> FieldSetDelegateCache = new ConcurrentDictionary<FieldInfo, Delegate>(); // Property private static readonly ConcurrentDictionary<(Type T, string name), PropertyInfo> PropertyCache = new ConcurrentDictionary<(Type T, string name), PropertyInfo>(); private static readonly ConcurrentDictionary<PropertyInfo, Delegate> PropertyGetDelegateCache = new ConcurrentDictionary<PropertyInfo, Delegate>(); private static readonly ConcurrentDictionary<PropertyInfo, Delegate> PropertySetDelegateCache = new ConcurrentDictionary<PropertyInfo, Delegate>(); // Method private static readonly ConcurrentDictionary<(Type T, string name), MethodInfo> MethodCache = new ConcurrentDictionary<(Type T, string name), MethodInfo>(); private static readonly ConcurrentDictionary<(Type T, string name, Type[] argumentTypes), MethodInfo> OverloadedMethodCache = new ConcurrentDictionary<(Type T, string name, Type[] argumentTypes), MethodInfo>(); private static readonly ConcurrentDictionary<MethodInfo, FastReflectionDelegate> DelegateCache = new ConcurrentDictionary<MethodInfo, FastReflectionDelegate>(); // Class private static readonly ConcurrentDictionary<(Type T, Type[] argumentTypes), ConstructorInfo> ConstructorCache = new ConcurrentDictionary<(Type T, Type[] argumentTypes), ConstructorInfo>(); private static readonly ConcurrentDictionary<(Type T, string name), Type> NestedTypeCache = new ConcurrentDictionary<(Type T, string name), Type>(); // Helper methods private static TValue GetOrAddOnNull<TKey, TValue>(this ConcurrentDictionary<TKey, TValue> dict, TKey key, Func<TKey, TValue> factory) { if (dict.TryGetValue(key, out var val) && val != null) return val; return dict[key] = factory(key); } #endregion #region Field /// <summary> /// Gets the <see cref="FieldInfo"/> of the type by name and caches it /// </summary> /// <typeparam name="T">The type to search</typeparam> /// <param name="name">The name of the field to find</param> /// <returns></returns> public static FieldInfo GetFieldCached<T>(string name) => typeof(T).GetFieldCached(name); /// <summary> /// Gets the <see cref="FieldInfo" /> of the type by name and caches it /// </summary> /// <param name="T">The type to search</param> /// <param name="name">The name of the field to find</param> /// <returns></returns> public static FieldInfo GetFieldCached(this Type T, string name) => FieldCache.GetOrAddOnNull((T, name), x => x.T.GetFieldFull(x.name) ?? throw new Exception($"Could not find {nameof(FieldInfo)} on {T.FullName} with the name {name}")); /// <summary> /// Gets the value of the field on the object /// </summary> /// <typeparam name="TReturn">The type of the return value</typeparam> /// <param name="fieldName">The name of the field to get the value of</param> /// <param name="instance">The object to get the field's value from</param> /// <returns></returns> public static TReturn GetFieldValue<TReturn>(this object instance, string fieldName) => instance.GetType() .GetFieldCached(fieldName) .GetFieldGetDelegate<TReturn>() (instance); /// <summary> /// Gets the value of the specified static field on the specified static type /// </summary> /// <typeparam name="TReturn">The return type</typeparam> /// <param name="staticType">The name of the static field to get the value of</param> /// <param name="fieldName">The type to get the specified static field's value on</param> /// <returns></returns> public static TReturn GetFieldValue<TReturn>(this Type staticType, string fieldName) => staticType .GetFieldCached(fieldName) .GetFieldGetDelegate<TReturn>() (null); /// <summary> /// Sets the value of the specified field on the specified object; if the object is a struct use /// <see cref="SetStructFieldValue{TInstance, TValue}(ref TInstance, string, TValue)"/> instead /// </summary> /// <typeparam name="TValue">The type of the value to set</typeparam> /// <param name="instance">The name of the field to set the value of</param> /// <param name="fieldName">The type to set the specified field's value on</param> /// <param name="value">The value to set</param> /// <returns></returns> public static void SetFieldValue<TValue>(this object instance, string fieldName, TValue value) => instance.GetType() .GetFieldCached(fieldName) .GetFieldSetDelegate<TValue>() (instance, value); /// <summary> /// Sets the value of the specified static field on the specified static type /// </summary> /// <typeparam name="TValue">The type of the value to set</typeparam> /// <param name="staticType">The name of the static field to set the value of</param> /// <param name="fieldName">The type to set the specified static field's value on</param> /// <param name="value">The value to set</param> /// <returns></returns> public static void SetFieldValue<TValue>(this Type staticType, string fieldName, TValue value) => staticType .GetFieldCached(fieldName) .GetFieldSetDelegate<TValue>() (null, value); /// <summary> /// Sets the value of the specified field on the specified struct /// </summary> /// <typeparam name="TInstance">The type of the instance of the struct</typeparam> /// <typeparam name="TValue">The type of the value to set</typeparam> /// <param name="instance">The name of the field to set the value of</param> /// <param name="fieldName">The type to set the specified field's value on</param> /// <param name="value">The value to set the field to</param> /// <returns></returns> public static void SetStructFieldValue<TInstance, TValue>(this ref TInstance instance, string fieldName, TValue value) where TInstance : struct => typeof(TInstance) .GetFieldCached(fieldName) .GetFieldSetDelegateRef<TInstance, TValue>() (ref instance, value); /// <summary> /// Gets the <see cref="FieldInfo"/> on the specified <see cref="Type"/> and searches base types if not found. /// </summary> /// <param name="T">The <see cref="Type"/> to search and get base types from</param> /// <param name="name">The name of the property to search for.</param> /// <returns></returns> private static FieldInfo GetFieldFull(this Type T, string name) { while (T != null) { var fieldInfo = T.GetField(name, AllFlags); if (fieldInfo != null) { return fieldInfo; } T = T.BaseType; } return null; } private static T GetMemberFull<T>(this Type type, string name) where T : MemberInfo { while (type != null) { var fieldInfo = type.GetMember(name, AllFlags); if (fieldInfo != null) { return (T)fieldInfo.First(); } type = type.BaseType; } return null; } private static GetDelegate<TReturn> GetFieldGetDelegate<TReturn>(this FieldInfo field) => FieldGetDelegateCache.GetOrAdd(field, x => x.CreateGetDelegate<TReturn>()) .CastDelegate<GetDelegate<TReturn>>(); private static SetDelegate<TValue> GetFieldSetDelegate<TValue>(this FieldInfo field) => FieldSetDelegateCache.GetOrAdd(field, x => x.CreateSetDelegate<TValue>()) .CastDelegate<SetDelegate<TValue>>(); private static SetDelegateRef<TInstance, TValue> GetFieldSetDelegateRef<TInstance, TValue>(this FieldInfo field) where TInstance : struct => FieldSetDelegateCache.GetOrAdd(field, x => x.CreateSetDelegateRef<TInstance, TValue>()) .CastDelegate<SetDelegateRef<TInstance, TValue>>(); #endregion #region Property /// <summary> /// Gets the <see cref="PropertyInfo"/> of the type by name /// </summary> /// <typeparam name="T">The type on which to find the property</typeparam> /// <param name="name">The name of the property to get</param> /// <returns></returns> public static PropertyInfo GetPropertyCached<T>(string name) => typeof(T).GetPropertyCached(name); /// <summary> /// Gets the <see cref="PropertyInfo"/> of the type by name /// </summary> /// <param name="T">The type to get the <see cref="PropertyInfo"/> from</param> /// <param name="name">The name of the property to get</param> /// <returns></returns> public static PropertyInfo GetPropertyCached(this Type T, string name) => PropertyCache.GetOrAddOnNull((T, name), x => x.T.GetProperty(x.name, AllFlags)); /// <summary> /// Gets the value of the property on the specified object; if the object is a struct use /// <see cref="GetStructPropertyValue{TInstance, TValue}(ref TInstance, string)"></see> instead /// </summary> /// <typeparam name="TReturn">The type of the return value</typeparam> /// <param name="instance">The object to get the property's value from</param> /// <param name="propName">The name of the field to get the value of</param> /// <returns></returns> public static TReturn GetPropertyValue<TReturn>(this object instance, string propName) => instance.GetType() .GetPropertyCached(propName) .GetPropertyGetDelegate<TReturn>() (instance); /// <summary> /// Gets the value of the static property on the specified static type /// </summary> /// <typeparam name="TReturn">The return type</typeparam> /// <param name="staticType">The name of the static field to get the value of</param> /// <param name="propName">The type to get the specified static property's value on</param> /// <returns></returns> public static TReturn GetPropertyValue<TReturn>(this Type staticType, string propName) => staticType .GetPropertyCached(propName) .GetPropertyGetDelegate<TReturn>() (null); /// <summary> /// Sets the value of the property on the specified class; if you're setting the property on a /// struct use <see cref="SetStructPropertyValue{TInstance, TValue}(ref TInstance, string, TValue)"/> instead /// </summary> /// <typeparam name="TValue">The type of the value to set</typeparam> /// <param name="instance">The name of the field to set the value of</param> /// <param name="propName">The type to set the specified property's value on</param> /// <param name="value">The value to set</param> /// <returns></returns> public static void SetPropertyValue<TValue>(this object instance, string propName, TValue value) => instance.GetType() .GetPropertyCached(propName)? .GetPropertySetDelegate<TValue>() (instance, value); /// <summary> /// Sets the value of the static property on the specified static class /// </summary> /// <typeparam name="TValue">The type of the value to set</typeparam> /// <param name="staticType">The name of the static field to set the value of</param> /// <param name="propName">The type to set the specified static property's value on</param> /// <param name="value">The value to set the property to</param> /// <returns></returns> public static void SetPropertyValue<TValue>(this Type staticType, string propName, TValue value) => staticType.GetPropertyCached(propName)? .GetPropertySetDelegate<TValue>() (null, value); /// <summary> /// Sets the value of the specified property on the specified struct /// </summary> /// <typeparam name="TInstance">The type of the instance of the struct</typeparam> /// <typeparam name="TValue">The type of the value to set</typeparam> /// <param name="instance">The name of the field to set the value of</param> /// <param name="propName">The type to set the specified property's value on</param> /// <param name="value">The value to set the property to</param> /// <returns></returns> public static void SetStructPropertyValue<TInstance, TValue>(this ref TInstance instance, string propName, TValue value) where TInstance : struct => typeof(TInstance) .GetPropertyCached(propName) .GetPropertySetDelegateRef<TInstance, TValue>() (ref instance, value); /// <summary> /// Gets the value of the specified property on the specified struct /// </summary> /// <typeparam name="TInstance">The type of the struct</typeparam> /// <typeparam name="TValue">The type of the value to set</typeparam> /// <param name="instance">The name of the field to set the value of</param> /// <param name="propName">The type to set the specified property's value on</param> /// <returns></returns> public static TValue GetStructPropertyValue<TInstance, TValue>(this ref TInstance instance, string propName) where TInstance : struct => typeof(TInstance) .GetPropertyCached(propName) .GetPropertyGetDelegateRef<TInstance, TValue>() (ref instance); private static GetDelegate<TReturn> GetPropertyGetDelegate<TReturn>(this PropertyInfo property) => PropertyGetDelegateCache.GetOrAdd(property, prop => prop.CreateGetDelegate<TReturn>()) .CastDelegate<GetDelegate<TReturn>>(); private static GetDelegateRef<TInstance, TReturn> GetPropertyGetDelegateRef<TInstance, TReturn>(this PropertyInfo property) where TInstance : struct => PropertyGetDelegateCache.GetOrAdd(property, prop => prop.CreateGetDelegate<TInstance, TReturn>()) .CastDelegate<GetDelegateRef<TInstance, TReturn>>(); private static SetDelegate<TValue> GetPropertySetDelegate<TValue>(this PropertyInfo property) => PropertySetDelegateCache.GetOrAdd(property, prop => prop.CreateSetDelegate<TValue>()) .CastDelegate<SetDelegate<TValue>>(); private static SetDelegateRef<TInstance, TValue> GetPropertySetDelegateRef<TInstance, TValue>( this PropertyInfo property) where TInstance : struct => PropertySetDelegateCache.GetOrAdd(property, prop => prop.CreateSetDelegateRef<TInstance, TValue>()) .CastDelegate<SetDelegateRef<TInstance, TValue>>(); #endregion #region Method /// <summary> /// Gets the method on the specified type and caches it /// </summary> /// <typeparam name="T">The type to search</typeparam> /// <param name="name">The name of the method to find</param> /// <returns></returns> public static MethodInfo GetMethodCached<T>(string name) => typeof(T).GetMethodCached(name); /// <summary> /// Gets the method on the specified static type and caches it /// </summary> /// <param name="T">The type to search</param> /// <param name="name">The name of the method to find</param> /// <returns></returns> public static MethodInfo GetMethodCached(this Type T, string name) => MethodCache.GetOrAddOnNull((T, name), x => x.T.GetMethod(x.name, AllFlags) ?? throw new Exception($"Could not find {nameof(MethodInfo)} on {T.FullName} with the name {name}")); /// <summary> /// Gets the method on the specified type and caches it. This overload is used when the method is ambiguous /// </summary> /// <typeparam name="T">The type to search</typeparam> /// <param name="name">The name of the method to find</param> /// <param name="argumentTypes">The types of the argument</param> /// <returns></returns> public static MethodInfo GetMethodCached<T>(string name, Type[] argumentTypes) => typeof(T).GetMethodCached(name, argumentTypes); /// <summary> /// Gets the method on the specified static type and caches it. This overload is used when the method is ambiguous /// </summary> /// <param name="T">The type to search</param> /// <param name="name">The name of the method to find</param> /// <param name="argumentTypes">The types of the argument</param> public static MethodInfo GetMethodCached(this Type T, string name, Type[] argumentTypes) => OverloadedMethodCache.GetOrAddOnNull((T, name, argumentTypes), x => x.T.GetMethod(x.name, AllFlags, null, x.argumentTypes, null) ?? throw new Exception($"Could not find {nameof(MethodInfo)} on {T.FullName} with the name {name} and arguments: " + $"{string.Join(",", argumentTypes.Select(a => a.FullName))}")); /// <summary> /// Invoke a method on the specified object by name /// </summary> /// <typeparam name="TReturn">The return type of the method</typeparam> /// <param name="instance">The object to invoke the method on</param> /// <param name="methodName">The name of the method to invoke</param> /// <returns></returns> public static TReturn InvokeMethod<TReturn>(this object instance, string methodName) => instance.InvokeMethod<TReturn>(methodName, null); /// <summary> /// Invoke a static method on the specified type by name /// </summary> /// <typeparam name="TReturn">The return type of the method</typeparam> /// <param name="staticType">The static type to search</param> /// <param name="methodName">The name of the method to invoke</param> /// <returns></returns> public static TReturn InvokeMethod<TReturn>(this Type staticType, string methodName) => staticType.InvokeMethod<TReturn>(methodName, null); /// <summary> /// Invoke a method on the specified object by name /// </summary> /// <param name="instance">The object to invoke the method on</param> /// <param name="methodName">The name of the method to invoke</param> public static void InvokeMethod(this object instance, string methodName) => instance.InvokeMethod<object>(methodName); /// <summary> /// Invoke a static method on the specified type by name /// </summary> /// <param name="staticType">The static type to search</param> /// <param name="methodName">The name of the method to invoke</param> public static void InvokeMethod(this Type staticType, string methodName) => staticType.InvokeMethod<object>(methodName); /// <summary> /// Invoke a method on the specified object by name with parameters /// </summary> /// <typeparam name="TReturn">The return type of the method</typeparam> /// <param name="instance">The object to invoke the method on</param> /// <param name="methodName">The name of the method to invoke</param> /// <param name="methodParams"></param> /// <returns></returns> public static TReturn InvokeMethod<TReturn>(this object instance, string methodName, params object[] methodParams) { var methodInfo = (methodParams == null ? instance.GetType() .GetMethodCached(methodName) : instance.GetType() .GetMethodCached(methodName, methodParams.Select(x => x.GetType()).ToArray()) ) ?? throw new Exception($"Could not find method on type {instance.GetType()} with the name of {methodName} with the arguments specified."); return (TReturn)methodInfo.GetMethodDelegateCached()(instance, methodParams); } /// <summary> /// Invoke a static method on the specified type by name with parameters /// </summary> /// <typeparam name="TReturn">The return type of the method</typeparam> /// <param name="staticType">The static type to search</param> /// <param name="methodName">The name of the method to invoke</param> /// <param name="methodParams">The method parameters</param> /// <returns></returns> public static TReturn InvokeMethod<TReturn>(this Type staticType, string methodName, params object[] methodParams) { var methodInfo = (methodParams == null ? staticType .GetMethodCached(methodName) : staticType .GetMethodCached(methodName, methodParams.Select(x => x.GetType()).ToArray())) ?? throw new Exception($"Could not find method on type {staticType} with the name of {methodName} with the arguments specified."); return (TReturn)methodInfo.GetMethodDelegateCached()(null, methodParams); } /// <summary> /// Invoke a method on the specified object by name with parameters /// </summary> /// <param name="instance">The object to invoke the method on</param> /// <param name="methodName">The name of the method to invoke</param> /// <param name="methodParams"></param> public static void InvokeMethod(this object instance, string methodName, params object[] methodParams) => instance.InvokeMethod<object>(methodName, methodParams); /// <summary> /// Invoke a static method on the specified type by name with parameters /// </summary> /// <param name="staticType">The static type to search</param> /// <param name="methodName">The name of the method to invoke</param> /// <param name="methodParams"></param> public static void InvokeMethod(this Type staticType, string methodName, params object[] methodParams) => staticType.InvokeMethod<object>(methodName, methodParams); private static FastReflectionDelegate GetMethodDelegateCached(this MethodInfo methodInfo) => DelegateCache.GetOrAdd(methodInfo, method => method.CreateFastDelegate()); #endregion #region Class /// <summary> /// Gets the constructor on the specified type with specified arguments and caches it /// </summary> /// <typeparam name="T">The type to search</typeparam> /// <param name="argumentTypes">The types of the arguments on the constructor to find</param> /// <returns></returns> public static ConstructorInfo GetConstructorCached<T>(Type[] argumentTypes) => GetConstructorCached(typeof(T), argumentTypes); /// <summary> /// Gets the constructor on the specified static type with specified arguments and caches it /// </summary> /// <param name="T">The type to search</param> /// <param name="argumentTypes">The types of the arguments on the constructor to find</param> /// <returns></returns> public static ConstructorInfo GetConstructorCached(this Type T, Type[] argumentTypes) => ConstructorCache.GetOrAddOnNull((T, argumentTypes), x => x.T.GetConstructor(x.argumentTypes) ?? throw new Exception($"Could not find {nameof(ConstructorInfo)} on {T.FullName} with the arguments {string.Join(",", argumentTypes.Select(a => a.FullName))}")); /// <summary> /// Gets the nested type on the specified type /// </summary> /// <typeparam name="T">The type to search</typeparam> /// <param name="name">The name of the nested type to find</param> /// <returns></returns> public static Type GetNestedType<T>(string name) => typeof(T).GetNestedTypeCached(name); /// <summary> /// Gets the nested type on the specified type /// </summary> /// <typeparam name="T">The type to search</typeparam> /// <param name="name">The name of the nested type to find</param> /// <returns></returns> public static Type GetNestedTypeCached<T>(string name) => typeof(T).GetNestedTypeCached(name); /// <summary> /// Gets the nested type on the specified static type /// </summary> /// <param name="T">The static type to search</param> /// <param name="name">The name of the nested type to find</param> /// <returns></returns> public static Type GetNestedTypeCached(this Type T, string name) => NestedTypeCache.GetOrAddOnNull((T, name), x => x.T.GetNestedType(x.name, AllFlags) ?? throw new Exception($"Could not find nested {nameof(Type)} on {T.FullName} with the name {name}")); /// <summary> /// Instatiates the specified type /// </summary> /// <param name="type">The type to instantiate</param> /// <returns></returns> public static object Instantiate(this Type type) => Activator.CreateInstance(type, true); /// <summary> /// Instatiates the specified type with specified constructor arguments /// </summary> /// <param name="type">The type to instantiate</param> /// <param name="constructorArguments">The constructor arguments</param> /// <returns></returns> public static object Instantiate(this Type type, params object[] constructorArguments) => type.GetConstructorCached(constructorArguments.Select(x => x.GetType()).ToArray()) .Invoke(constructorArguments); /// <summary> /// Instantiates the specified generic type /// </summary> /// <typeparam name="TClass">The type to instantiate</typeparam> /// <param name="typeArgument">The type of the generic type argument</param> /// <returns></returns> public static object InstantiateGeneric<TClass>(this Type typeArgument) => typeof(TClass).MakeGenericType(typeArgument).Instantiate(); /// <summary> /// Instantiates the specified generic types /// </summary> /// <typeparam name="TClass">The type to instantiate</typeparam> /// <param name="typeArgument">The types of the generic type arguments</param> /// <returns></returns> public static object InstantiateGeneric<TClass>(this Type[] typeArgument) => typeof(TClass).MakeGenericType(typeArgument).Instantiate(); /// <summary> /// Instantiates a list of the specified generic type /// </summary> /// <param name="type"></param> /// <returns></returns> public static IList InstantiateList(this Type type) => (IList)typeof(List<>).MakeGenericType(type).Instantiate(); #endregion #region Fast Reflection private static GetDelegate<TReturn> CreateGetDelegate<TReturn>(this FieldInfo field) { if (field == null) { throw new ArgumentException("Field cannot be null.", nameof(field)); } if (!typeof(TReturn).IsAssignableFrom(field.FieldType)) { throw new Exception($"Field type {field.FieldType} does not match the requested type {typeof(TReturn)}."); } using (var method = new DynamicMethodDefinition($"{field} Getter", typeof(TReturn), new[] { typeof(object) })) { var il = method.GetILProcessor(); if (!field.IsStatic) { il.Emit(OpCodes.Ldarg_0); if (field.DeclaringType.GetTypeInfo().IsValueType) { il.Emit(OpCodes.Unbox_Any, field.DeclaringType); } } il.Emit(!field.IsStatic ? OpCodes.Ldfld : OpCodes.Ldsfld, field); il.Emit(OpCodes.Ret); return (GetDelegate<TReturn>)method.Generate().CreateDelegate(typeof(GetDelegate<TReturn>)); } } private static SetDelegate<TValue> CreateSetDelegate<TValue>(this FieldInfo field) { if (field == null) { throw new ArgumentException("Field cannot be null.", nameof(field)); } if (!field.FieldType.IsAssignableFrom(typeof(TValue))) { throw new Exception($"Value type type {typeof(TValue)} does not match the requested type {field.FieldType}."); } using (var method = new DynamicMethodDefinition($"{field} Setter", typeof(void), new[] { typeof(object), typeof(TValue) })) { var il = method.GetILProcessor(); if (!field.IsStatic) { il.Emit(OpCodes.Ldarg_0); } il.Emit(OpCodes.Ldarg_1); il.Emit(!field.IsStatic ? OpCodes.Stfld : OpCodes.Stsfld, field); il.Emit(OpCodes.Ret); return (SetDelegate<TValue>)method.Generate().CreateDelegate(typeof(SetDelegate<TValue>)); } } private static SetDelegateRef<TInstance, TValue> CreateSetDelegateRef<TInstance, TValue>(this FieldInfo field) where TInstance : struct { if (field == null) { throw new ArgumentException("Field cannot be null.", nameof(field)); } if (field.FieldType != typeof(TValue)) { throw new Exception($"Value type type {typeof(TValue)} does not match the requested type {field.FieldType}."); } using (var method = new DynamicMethodDefinition($"{field} SetterByRef", typeof(void), new[] { typeof(TInstance).MakeByRefType(), typeof(TValue) })) { var il = method.GetILProcessor(); if (!field.IsStatic) { il.Emit(OpCodes.Ldarg_0); } il.Emit(OpCodes.Ldarg_1); il.Emit(!field.IsStatic ? OpCodes.Stfld : OpCodes.Stsfld, field); il.Emit(OpCodes.Ret); return (SetDelegateRef<TInstance, TValue>)method.Generate().CreateDelegate(typeof(SetDelegateRef<TInstance, TValue>)); } } private static GetDelegate<TReturn> CreateGetDelegate<TReturn>(this PropertyInfo property) { if (property == null) { throw new ArgumentException("Property cannot be null.", nameof(property)); } if (!typeof(TReturn).IsAssignableFrom(property.PropertyType)) { throw new Exception($"Field type {property.PropertyType} does not match the requested type {typeof(TReturn)}."); } using (var method = new DynamicMethodDefinition($"{property} Getter", typeof(TReturn), new[] { typeof(object) })) { var il = method.GetILProcessor(); var getMethod = property.GetGetMethod(nonPublic: true); if (!getMethod.IsStatic) { il.Emit(OpCodes.Ldarg_0); } il.Emit(OpCodes.Call, getMethod); il.Emit(OpCodes.Ret); return (GetDelegate<TReturn>)method.Generate().CreateDelegate(typeof(GetDelegate<TReturn>)); } } private static GetDelegateRef<TInstance, TReturn> CreateGetDelegate<TInstance, TReturn>(this PropertyInfo property) where TInstance : struct { if (property == null) { throw new ArgumentException("Property cannot be null.", nameof(property)); } if (!typeof(TReturn).IsAssignableFrom(property.PropertyType)) { throw new Exception($"Field type {property.PropertyType} does not match the requested type {typeof(TReturn)}."); } using (var method = new DynamicMethodDefinition($"{property} Getter", typeof(TReturn), new[] { typeof(TInstance).MakeByRefType() })) { var il = method.GetILProcessor(); // Cache this as well? var getMethod = property.GetGetMethod(nonPublic: true); if (!getMethod.IsStatic) { il.Emit(OpCodes.Ldarg_0); } il.Emit(OpCodes.Call, getMethod); il.Emit(OpCodes.Ret); return (GetDelegateRef<TInstance, TReturn>)method.Generate().CreateDelegate(typeof(GetDelegateRef<TInstance, TReturn>)); } } private static SetDelegate<TValue> CreateSetDelegate<TValue>(this PropertyInfo property) { if (property == null) { throw new ArgumentException("Property cannot be null.", nameof(property)); } if (!property.PropertyType.IsAssignableFrom(typeof(TValue))) { throw new Exception($"Value type type {typeof(TValue)} does not match the requested type {property.PropertyType}."); } using (var method = new DynamicMethodDefinition($"{property} Setter", typeof(void), new[] { typeof(object), typeof(TValue) })) { var il = method.GetILProcessor(); var setMethod = property.GetSetMethod(true); if (!setMethod.IsStatic) { il.Emit(OpCodes.Ldarg_0); } il.Emit(OpCodes.Ldarg_1); il.Emit(OpCodes.Call, setMethod); il.Emit(OpCodes.Ret); return (SetDelegate<TValue>)method.Generate().CreateDelegate(typeof(SetDelegate<TValue>)); } } private static SetDelegateRef<TInstance, TValue> CreateSetDelegateRef<TInstance, TValue>(this PropertyInfo property) where TInstance : struct { if (property == null) { throw new ArgumentException("Property cannot be null.", nameof(property)); } if (!property.PropertyType.IsAssignableFrom(typeof(TValue))) { throw new Exception($"Value type type {typeof(TValue)} does not match the requested type {property.PropertyType}."); } using (var method = new DynamicMethodDefinition($"{property} SetterByRef", typeof(void), new[] { typeof(TInstance).MakeByRefType(), typeof(TValue) })) { var il = method.GetILProcessor(); var setMethod = property.GetSetMethod(true); if (!setMethod.IsStatic) { il.Emit(OpCodes.Ldarg_0); } il.Emit(OpCodes.Ldarg_1); il.Emit(OpCodes.Call, setMethod); il.Emit(OpCodes.Ret); return (SetDelegateRef<TInstance, TValue>)method.Generate().CreateDelegate(typeof(SetDelegateRef<TInstance, TValue>)); } } // Partial hack from https://github.com/0x0ade/MonoMod/blob/master/MonoMod.Utils/FastReflectionHelper.cs // to get fast call delegates //private static CallDelegate GenerateCallDelegate(this MethodInfo method) { // if (method == null) { // throw new ArgumentException("Method cannot be null.", nameof(method)); // } // var dmd = new DynamicMethodDefinition( // $"CallDelegate<{method.Name}>", typeof(object), new[] { typeof(object), typeof(object[]) }); // var il = dmd.GetILProcessor(); // var args = method.GetParameters(); // if (!method.IsStatic) { // il.Emit(OpCodes.Ldarg_0); // if (method.DeclaringType.GetTypeInfo().IsValueType) { // il.Emit(OpCodes.Unbox_Any, method.DeclaringType); // } // } // for (var i = 0; i < args.Length; i++) { // var argType = args[i].ParameterType; // var argIsByRef = argType.IsByRef; // if (argIsByRef) // argType = argType.GetElementType(); // var argIsValueType = argType.GetTypeInfo().IsValueType; // if (argIsByRef && argIsValueType) { // // Used later when storing back the reference to the new box in the array. // il.Emit(OpCodes.Ldarg_1); // il.EmitFast_Ldc_I4(i); // } // il.Emit(OpCodes.Ldarg_1); // il.EmitFast_Ldc_I4(i); // if (argIsByRef && !argIsValueType) { // il.Emit(OpCodes.Ldelema, typeof(object)); // } // else { // il.Emit(OpCodes.Ldelem_Ref); // if (!argIsValueType) continue; // il.Emit(!argIsByRef ? OpCodes.Unbox_Any : OpCodes.Unbox, argType); // } // } // if (method.IsFinal || !method.IsVirtual) { // il.Emit(OpCodes.Call, method); // } // else { // il.Emit(OpCodes.Callvirt, method); // } // var returnType = method.IsConstructor ? method.DeclaringType : method.ReturnType; // if (returnType != typeof(void)) { // if (returnType.GetTypeInfo().IsValueType) { // il.Emit(OpCodes.Box, returnType); // } // } // else { // il.Emit(OpCodes.Ldnull); // } // il.Emit(OpCodes.Ret); // return (CallDelegate) dmd.Generate().CreateDelegate(typeof(CallDelegate)); //} // https://github.com/0x0ade/MonoMod/blob/master/MonoMod.Utils/FastReflectionHelper.cs public static void EmitFast_Ldc_I4(this ILProcessor il, int value) { switch (value) { case -1: il.Emit(OpCodes.Ldc_I4_M1); return; case 0: il.Emit(OpCodes.Ldc_I4_0); return; case 1: il.Emit(OpCodes.Ldc_I4_1); return; case 2: il.Emit(OpCodes.Ldc_I4_2); return; case 3: il.Emit(OpCodes.Ldc_I4_3); return; case 4: il.Emit(OpCodes.Ldc_I4_4); return; case 5: il.Emit(OpCodes.Ldc_I4_5); return; case 6: il.Emit(OpCodes.Ldc_I4_6); return; case 7: il.Emit(OpCodes.Ldc_I4_7); return; case 8: il.Emit(OpCodes.Ldc_I4_8); return; } if (value > -129 && value < 128) il.Emit(OpCodes.Ldc_I4_S, (sbyte)value); else il.Emit(OpCodes.Ldc_I4, value); } public static byte ReadLocalIndex(OpCode opCode, object operand) { if (opCode == OpCodes.Ldloc_0 || opCode == OpCodes.Stloc_0) { return 0; } if (opCode == OpCodes.Ldloc_1 || opCode == OpCodes.Stloc_1) { return 1; } if (opCode == OpCodes.Ldloc_2 || opCode == OpCodes.Stloc_2) { return 2; } if (opCode == OpCodes.Ldloc_3 || opCode == OpCodes.Stloc_3) { return 3; } if (opCode == OpCodes.Ldloc_S || opCode == OpCodes.Stloc_S) { return (byte)operand; } throw new Exception($"Could not read index for opcode and operand: {opCode} - {operand}"); } #endregion } }
46.61989
178
0.592212
[ "MIT" ]
kylewill0725/R2API
R2API/Utils/Reflection.cs
42,193
C#
using CommonServiceLocator; using DevelopmentInProgress.TradeView.Core.Interfaces; using DevelopmentInProgress.TradeView.Data; using DevelopmentInProgress.TradeView.Data.File; using DevelopmentInProgress.TradeView.Service; using DevelopmentInProgress.TradeView.Wpf.Common.Cache; using DevelopmentInProgress.TradeView.Wpf.Common.Chart; using DevelopmentInProgress.TradeView.Wpf.Common.Helpers; using DevelopmentInProgress.TradeView.Wpf.Common.Manager; using DevelopmentInProgress.TradeView.Wpf.Common.Services; using DevelopmentInProgress.TradeView.Wpf.Common.ViewModel; using DevelopmentInProgress.TradeView.Wpf.Configuration.Utility; using DevelopmentInProgress.TradeView.Wpf.Controls.Messaging; using DevelopmentInProgress.TradeView.Wpf.Host.Controller.Context; using DevelopmentInProgress.TradeView.Wpf.Host.Controller.Navigation; using DevelopmentInProgress.TradeView.Wpf.Host.Controller.RegionAdapters; using DevelopmentInProgress.TradeView.Wpf.Host.Controller.View; using DevelopmentInProgress.TradeView.Wpf.Host.Controller.ViewModel; using DevelopmentInProgress.TradeView.Wpf.Host.Logger; using DevelopmentInProgress.TradeView.Wpf.Strategies.Utility; using DevelopmentInProgress.TradeView.Wpf.Trading.ViewModel; using Prism.Ioc; using Prism.Logging; using Prism.Modularity; using Prism.Regions; using Prism.Unity; using Serilog; using System; using System.ComponentModel; using System.IO; using System.Windows; using Xceed.Wpf.AvalonDock; namespace DevelopmentInProgress.TradeView.Wpf.Host { /// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App : PrismApplication { protected override void OnStartup(StartupEventArgs e) { base.OnStartup(e); AppDomain currentDomain = AppDomain.CurrentDomain; currentDomain.UnhandledException += new UnhandledExceptionEventHandler(UnhandledExceptionHandler); } protected override IModuleCatalog CreateModuleCatalog() { using Stream xamlStream = File.OpenRead("Configuration/ModuleCatalog.xaml"); var moduleCatalog = ModuleCatalog.CreateFromXaml(xamlStream); return moduleCatalog; } protected override async void RegisterTypes(IContainerRegistry containerRegistry) { Serilog.Core.Logger logger = new LoggerConfiguration() .ReadFrom.AppSettings() .CreateLogger(); containerRegistry.RegisterInstance<ILogger>(logger); containerRegistry.RegisterSingleton<ILoggerFacade, LoggerFacade>(); containerRegistry.RegisterSingleton<NavigationManager>(); containerRegistry.RegisterSingleton<ModulesNavigationView>(); containerRegistry.RegisterSingleton<ModulesNavigationViewModel>(); containerRegistry.RegisterSingleton<ModuleNavigator>(); containerRegistry.Register<IViewContext, ViewContext>(); containerRegistry.RegisterSingleton<IExchangeApiFactory, ExchangeApiFactory>(); containerRegistry.Register<IExchangeService, ExchangeService>(); containerRegistry.Register<ITradeViewConfigurationAccounts, TradeViewConfigurationAccountsFile>(); containerRegistry.Register<ITradeViewConfigurationStrategy, TradeViewConfigurationStrategyFile>(); containerRegistry.Register<ITradeViewConfigurationServer, TradeViewConfigurationServerFile>(); containerRegistry.Register<IAccountsService, AccountsService>(); containerRegistry.Register<IStrategyService, StrategyService>(); containerRegistry.Register<ITradeServerService, TradeServerService>(); containerRegistry.Register<IWpfExchangeService, WpfExchangeService>(); containerRegistry.Register<ISymbolsCache, SymbolsCache>(); containerRegistry.RegisterSingleton<ISymbolsCacheFactory, SymbolsCacheFactory>(); containerRegistry.RegisterSingleton<IServerMonitorCache, ServerMonitorCache>(); containerRegistry.RegisterSingleton<IOrderBookHelperFactory, OrderBookHelperFactory>(); containerRegistry.RegisterSingleton<ITradeHelperFactory, TradeHelperFactory>(); containerRegistry.RegisterSingleton<IHelperFactoryContainer, HelperFactoryContainer>(); containerRegistry.RegisterSingleton<IChartHelper, ChartHelper>(); containerRegistry.Register<OrdersViewModel>(); containerRegistry.Register<AccountBalancesViewModel>(); containerRegistry.Register<AccountViewModel>(); containerRegistry.Register<SymbolsViewModel>(); containerRegistry.Register<TradePanelViewModel>(); containerRegistry.Register<IStrategyFileManager, StrategyFileManager>(); containerRegistry.Register<ISymbolsLoader, SymbolsLoader>(); containerRegistry.Register<IStrategyAssemblyManager, StrategyAssemblyManager>(); containerRegistry.Register<Strategies.ViewModel.SymbolsViewModel>(); containerRegistry.Register<Strategies.ViewModel.StrategyParametersViewModel>(); containerRegistry.RegisterSingleton<IHttpClientManager, HttpClientManager>(); var serverMonitorCache = Container.Resolve<IServerMonitorCache>(); serverMonitorCache.StartObservingServers(); var symbolsCacheFactory = Container.Resolve<ISymbolsCacheFactory>(); await symbolsCacheFactory.SubscribeAccountsAssets().ConfigureAwait(false); } protected override void ConfigureRegionAdapterMappings(RegionAdapterMappings regionAdapterMappings) { if(regionAdapterMappings == null) { throw new ArgumentNullException(nameof(regionAdapterMappings)); } regionAdapterMappings.RegisterMapping(typeof(DockingManager), new DockingManagerRegionAdapter(ServiceLocator.Current.GetInstance<IRegionBehaviorFactory>())); } protected override Window CreateShell() { return Container.Resolve<ShellWindow>(); } protected override void InitializeShell(Window shell) { if (shell == null) { throw new ArgumentNullException(nameof(shell)); } var modulesNavigationViewModel = Container.Resolve<ModulesNavigationViewModel>(); ((ShellWindow)shell).ModulesNavigationViewModel = modulesNavigationViewModel; Current.MainWindow = shell; Current.MainWindow.WindowState = WindowState.Maximized; Current.MainWindow.Show(); } private void UnhandledExceptionHandler(object sender, UnhandledExceptionEventArgs args) { Exception e = (Exception)args.ExceptionObject; var log = Container.Resolve<ILoggerFacade>(); log.Log(e.ToString(), Category.Exception, Priority.Low); } } }
44.974194
169
0.734184
[ "Apache-2.0" ]
CasparsTools/tradeview
src/DevelopmentInProgress.TradeView.Wpf.Host/App.xaml.cs
6,973
C#
using System; using System.Diagnostics; using System.Threading.Tasks; using CodeTest.Accounting.BFF.Core; using CodeTest.Accounting.BFF.Models; using CodeTest.Accounting.ServiceClients; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; namespace CodeTest.Accounting.BFF.Controllers { public class HomeController : Controller { private readonly ILogger<HomeController> _logger; private readonly CustomersServiceClient _customersServiceClient; private readonly AccountsOrchestrator _accountsOrchestrator; private readonly InformationOrchestrator _informationOrchestrator; public HomeController( ILogger<HomeController> logger, CustomersServiceClient customersServiceClient, AccountsOrchestrator accountsOrchestrator, InformationOrchestrator informationOrchestrator) { _logger = logger; _customersServiceClient = customersServiceClient; _accountsOrchestrator = accountsOrchestrator; _informationOrchestrator = informationOrchestrator; } public IActionResult Index() { var model = new AccountingViewModel { CreateCustomerDto = new CustomerDto(), OpenAccountDto = new OpenAccountDto() }; return View(model); } [Route("create-customer")] public async Task<IActionResult> CreateCustomer(AccountingViewModel input) { if (!ModelState.IsValid) { return RedirectToAction("Index"); } try { var customer = await _customersServiceClient.PostAsync(input.CreateCustomerDto); return RedirectToAction(nameof(UserInformation), new { customerId = customer.Id }); } catch (Exception e) { const string message = "Customer not valid!"; _logger.LogError(e, message); return BadRequest(message); } } [Route("open-account")] public async Task<IActionResult> OpenAccount(AccountingViewModel input) { if (!ModelState.IsValid) { return BadRequest(ModelState); } try { await _accountsOrchestrator.OpenAccountAsync(input.OpenAccountDto); } catch (CustomerNotValidException e) { const string message = "Customer not valid!"; _logger.LogError(e, message); return BadRequest(message); } return RedirectToAction(nameof(UserInformation), new { customerId = input.OpenAccountDto.CustomerId }); } [Route("user-information")] public async Task<IActionResult> UserInformation(int customerId) { var viewModel = new AccountingViewModel { OpenAccountDto = new OpenAccountDto { CustomerId = customerId }, CreateCustomerDto = new CustomerDto() }; if (customerId == default) { return BadRequest(); } viewModel.UserInfo = await _informationOrchestrator.GetUserInfoAsync(customerId); return View("Index", viewModel); } [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] public IActionResult Error() { return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); } } }
31.686441
115
0.590265
[ "MIT" ]
andreicojocaru/codetest-accounting
src/CodeTest.Accounting.BFF/Controllers/HomeController.cs
3,741
C#
// Copyright 2018 yinyue200.com // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using LottieUWP.Utils; namespace LottieUWP.Value { // ReSharper disable once UnusedMember.Global public class LottieInterpolatedFloatValue : LottieInterpolatedValue<float> { public LottieInterpolatedFloatValue(float startValue, float endValue) : base(startValue, endValue) { } public LottieInterpolatedFloatValue(float startValue, float endValue, IInterpolator interpolator) : base(startValue, endValue, interpolator) { } protected override float InterpolateValue(float startValue, float endValue, float progress) { return MiscUtils.Lerp(startValue, endValue, progress); } } }
35.378378
105
0.700535
[ "Apache-2.0" ]
cm4ker/LottieSharp
LottieSkiaSharp/Value/LottieInterpolatedFloatValue.cs
1,311
C#
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using Microsoft.Coyote.IO; namespace Microsoft.Coyote.SystematicTesting.Utilities { internal class DependencyGraph { private readonly Dictionary<string, string> AssemblyNameToFullPathMap = new Dictionary<string, string>(); public DependencyGraph(string rootFolder, HashSet<string> additionalAssemblies) { // here we assume the dependencies we need to instrument for assemblyUnderTest all live in the // same folder, or the user provides them with --instrument and --instrument-list options. var allNames = new HashSet<string>(Directory.GetFiles(rootFolder, "*.dll")); allNames.UnionWith(additionalAssemblies); // Because Assembly.GetReferencedAssemblies does not yet have the path (assembly resolution is complex), we will assume that // any assembly that matches a name in the executing directory is the referenced assembly that we need to also instrument. foreach (var path in allNames) { // Note: we cannot use allNames.ToDictionary because in some cases we have a *.exe and *.dll with the same name. var name = Path.GetFileNameWithoutExtension(path); if (!this.AssemblyNameToFullPathMap.ContainsKey(name)) { this.AssemblyNameToFullPathMap[name] = path; } else { Debug.WriteLine("Skipping {0}", path); } } } internal string[] GetDependencies(string assemblyUnderTest) { // Get the case-normalized directory name var result = new HashSet<string>(); this.GetDependencies(assemblyUnderTest, result); return result.ToArray(); } private void GetDependencies(string assemblyPath, HashSet<string> visited) { assemblyPath = Path.GetFullPath(assemblyPath); var assembly = Assembly.LoadFrom(assemblyPath); visited.Add(assemblyPath); foreach (var assemblyName in assembly.GetReferencedAssemblies()) { if (assemblyName.Name != "Microsoft.Coyote") { if (this.AssemblyNameToFullPathMap.ContainsKey(assemblyName.Name)) { var dependencyPath = this.AssemblyNameToFullPathMap[assemblyName.Name]; if (!visited.Contains(dependencyPath)) { this.GetDependencies(dependencyPath, visited); } } else if (assemblyName.Name != "mscorlib" && !assemblyName.Name.StartsWith("System")) { Error.Report($"Could not find dependent assembly '{assemblyName.ToString()}'"); } } } } } }
41.421053
136
0.585451
[ "MIT" ]
Youssef1313/coyote
Tools/Coyote/Utilities/DependencyGraph.cs
3,150
C#
 using System; using System.Collections.Generic; using System.Collections.Specialized; using Microsoft.VisualStudio.TestTools.UnitTesting; using PholioVisualisation.PholioObjects; using PholioVisualisation.RequestParameters; namespace PholioVisualisation.RequestParametersTest { [TestClass] public class DataDownloadParametersTest { [TestMethod] public void TestValid() { NameValueCollection nameValues = new NameValueCollection(); nameValues.Add(ParameterNames.ProfileId, "1"); nameValues.Add(ParameterNames.ParentAreaCode, AreaCodes.Sha_EastOfEngland); nameValues.Add(ParameterNames.AreaTypeId, (AreaTypeIds.Pct).ToString()); nameValues.Add(ParameterNames.ParentsToDisplay, ((int)ParentDisplay.NationalOnly).ToString()); DataDownloadParameters parameters = new DataDownloadParameters(nameValues); Assert.AreEqual(1, parameters.ProfileId); Assert.AreEqual(AreaCodes.Sha_EastOfEngland, parameters.ParentAreaCode); Assert.AreEqual(AreaTypeIds.Pct, parameters.AreaTypeId); Assert.AreEqual(ParentDisplay.NationalOnly, parameters.ParentsToDisplay); Assert.IsFalse(parameters.UseIndicatorIds); Assert.IsTrue(parameters.AreValid); } [TestMethod] public void TestUseIndicatorIds() { NameValueCollection nameValues = new NameValueCollection(); nameValues.Add(ParameterNames.ProfileId, "2"); nameValues.Add(DataDownloadParameters.ParameterIndicatorIds, "1,2"); nameValues.Add(ParameterNames.ParentAreaCode, AreaCodes.Sha_EastOfEngland); nameValues.Add(ParameterNames.AreaTypeId, (AreaTypeIds.Pct).ToString()); nameValues.Add(ParameterNames.ParentsToDisplay, ((int)ParentDisplay.NationalOnly).ToString()); DataDownloadParameters parameters = new DataDownloadParameters(nameValues); Assert.IsTrue(parameters.AreValid); Assert.IsTrue(parameters.UseIndicatorIds); } [TestMethod] public void TestParseParentsToDisplay() { // Valid Assert.IsTrue(DataDownloadParameters.IsParentDisplayValid((int)ParentDisplay.NationalAndRegional)); Assert.IsTrue(DataDownloadParameters.IsParentDisplayValid((int)ParentDisplay.RegionalOnly)); Assert.IsTrue(DataDownloadParameters.IsParentDisplayValid((int)ParentDisplay.NationalOnly)); // Invalid Assert.IsFalse(DataDownloadParameters.IsParentDisplayValid((int)ParentDisplay.Undefined)); Assert.IsFalse(DataDownloadParameters.IsParentDisplayValid(DataDownloadParameters.UndefinedInteger)); } } }
44.66129
113
0.710365
[ "MIT" ]
PublicHealthEngland/fingertips-open
PholioVisualisationWS/RequestParametersTest/DataDownloadParametersTest.cs
2,771
C#
#region license // Copyright (c) 2009 Rodrigo B. de Oliveira (rbo@acm.org) // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // * Neither the name of Rodrigo B. de Oliveira nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF // THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion // // DO NOT EDIT THIS FILE! // // This file was generated automatically by astgen.boo. // namespace Boo.Lang.Compiler.Ast { using System.Collections; using System.Runtime.Serialization; [System.Serializable] public partial class UnlessStatement : ConditionalStatement { protected Block _block; [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] new public UnlessStatement CloneNode() { return (UnlessStatement)Clone(); } /// <summary> /// <see cref="Node.CleanClone"/> /// </summary> [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] new public UnlessStatement CleanClone() { return (UnlessStatement)base.CleanClone(); } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override public NodeType NodeType { get { return NodeType.UnlessStatement; } } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override public void Accept(IAstVisitor visitor) { visitor.OnUnlessStatement(this); } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override public bool Matches(Node node) { if (node == null) return false; if (NodeType != node.NodeType) return false; var other = ( UnlessStatement)node; if (!Node.Matches(_modifier, other._modifier)) return NoMatch("UnlessStatement._modifier"); if (!Node.Matches(_condition, other._condition)) return NoMatch("UnlessStatement._condition"); if (!Node.Matches(_block, other._block)) return NoMatch("UnlessStatement._block"); return true; } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override public bool Replace(Node existing, Node newNode) { if (base.Replace(existing, newNode)) { return true; } if (_modifier == existing) { this.Modifier = (StatementModifier)newNode; return true; } if (_condition == existing) { this.Condition = (Expression)newNode; return true; } if (_block == existing) { this.Block = (Block)newNode; return true; } return false; } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override public object Clone() { UnlessStatement clone = (UnlessStatement)FormatterServices.GetUninitializedObject(typeof(UnlessStatement)); clone._lexicalInfo = _lexicalInfo; clone._endSourceLocation = _endSourceLocation; clone._documentation = _documentation; clone._isSynthetic = _isSynthetic; clone._entity = _entity; if (_annotations != null) clone._annotations = (Hashtable)_annotations.Clone(); if (null != _modifier) { clone._modifier = _modifier.Clone() as StatementModifier; clone._modifier.InitializeParent(clone); } if (null != _condition) { clone._condition = _condition.Clone() as Expression; clone._condition.InitializeParent(clone); } if (null != _block) { clone._block = _block.Clone() as Block; clone._block.InitializeParent(clone); } return clone; } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override internal void ClearTypeSystemBindings() { _annotations = null; _entity = null; if (null != _modifier) { _modifier.ClearTypeSystemBindings(); } if (null != _condition) { _condition.ClearTypeSystemBindings(); } if (null != _block) { _block.ClearTypeSystemBindings(); } } [System.Xml.Serialization.XmlElement] [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] public Block Block { get { if (_block == null) { _block = new Block(); _block.InitializeParent(this); } return _block; } set { if (_block != value) { _block = value; if (null != _block) { _block.InitializeParent(this); } } } } } }
28.722513
110
0.701786
[ "BSD-3-Clause" ]
rmartinho/boo
src/Boo.Lang.Compiler/Ast/Impl/UnlessStatementImpl.cs
5,486
C#
// // VTPixelTransferProperties.cs: Strongly Typed dictionary for VTPixelTransferPropertyKeys // // Authors: Alex Soto (alex.soto@xamarin.com) // // Copyright 2015 Xamarin Inc. // using System; using System.Runtime.InteropServices; using System.Collections.Generic; using CoreFoundation; using ObjCRuntime; using Foundation; using CoreMedia; using CoreVideo; using AVFoundation; // VTPixelTransferProperties are available in iOS 9 radar://22614931 https://trello.com/c/bTl6hRu9 namespace VideoToolbox { public partial class VTPixelTransferProperties : DictionaryContainer { public VTScalingMode ScalingMode { get { var key = GetNSStringValue (VTPixelTransferPropertyKeys.ScalingMode); if (key == null) return VTScalingMode.Unset; if (key == VTPixelTransferPropertyKeys.ScalingMode_Normal) return VTScalingMode.Normal; if (key == VTPixelTransferPropertyKeys.ScalingMode_CropSourceToCleanAperture) return VTScalingMode.CropSourceToCleanAperture; if (key == VTPixelTransferPropertyKeys.ScalingMode_Letterbox) return VTScalingMode.Letterbox; if (key == VTPixelTransferPropertyKeys.ScalingMode_Trim) return VTScalingMode.Trim; return VTScalingMode.Unset; } set { switch (value) { case VTScalingMode.Normal: SetStringValue (VTPixelTransferPropertyKeys.ScalingMode, VTPixelTransferPropertyKeys.ScalingMode_Normal); break; case VTScalingMode.CropSourceToCleanAperture: SetStringValue (VTPixelTransferPropertyKeys.ScalingMode, VTPixelTransferPropertyKeys.ScalingMode_CropSourceToCleanAperture); break; case VTScalingMode.Letterbox: SetStringValue (VTPixelTransferPropertyKeys.ScalingMode, VTPixelTransferPropertyKeys.ScalingMode_Letterbox); break; case VTScalingMode.Trim: SetStringValue (VTPixelTransferPropertyKeys.ScalingMode, VTPixelTransferPropertyKeys.ScalingMode_Trim); break; default: SetStringValue (VTPixelTransferPropertyKeys.ScalingMode, null); break; } } } public VTDownsamplingMode DownsamplingMode { get { var key = GetNSStringValue (VTPixelTransferPropertyKeys.DownsamplingMode); if (key == null) return VTDownsamplingMode.Unset; if (key == VTPixelTransferPropertyKeys.DownsamplingMode_Decimate) return VTDownsamplingMode.Decimate; if (key == VTPixelTransferPropertyKeys.DownsamplingMode_Average) return VTDownsamplingMode.Average; return VTDownsamplingMode.Unset; } set { switch (value) { case VTDownsamplingMode.Decimate: SetStringValue (VTPixelTransferPropertyKeys.DownsamplingMode, VTPixelTransferPropertyKeys.DownsamplingMode_Decimate); break; case VTDownsamplingMode.Average: SetStringValue (VTPixelTransferPropertyKeys.DownsamplingMode, VTPixelTransferPropertyKeys.DownsamplingMode_Average); break; default: SetStringValue (VTPixelTransferPropertyKeys.DownsamplingMode, null); break; } } } #if NET [SupportedOSPlatform ("ios10.0")] [SupportedOSPlatform ("tvos10.2")] [SupportedOSPlatform ("maccatalyst")] [SupportedOSPlatform ("macos")] #else [iOS (10,0)] #endif public VTColorPrimaries DestinationColorPrimaries { get { var key = GetNSStringValue (VTPixelTransferPropertyKeys.DestinationColorPrimaries); if (key == null) return VTColorPrimaries.Unset; if (key == CVImageBuffer.ColorPrimaries_ITU_R_709_2) return VTColorPrimaries.ItuR7092; if (key == CVImageBuffer.ColorPrimaries_EBU_3213) return VTColorPrimaries.Ebu3213; if (key == CVImageBuffer.ColorPrimaries_SMPTE_C) return VTColorPrimaries.SmpteC; if (key == CVImageBuffer.ColorPrimaries_P22) return VTColorPrimaries.P22; return VTColorPrimaries.Unset; } set { switch (value) { case VTColorPrimaries.ItuR7092: SetStringValue (VTPixelTransferPropertyKeys.DestinationColorPrimaries, CVImageBuffer.ColorPrimaries_ITU_R_709_2); break; case VTColorPrimaries.Ebu3213: SetStringValue (VTPixelTransferPropertyKeys.DestinationColorPrimaries, CVImageBuffer.ColorPrimaries_EBU_3213); break; case VTColorPrimaries.SmpteC: SetStringValue (VTPixelTransferPropertyKeys.DestinationColorPrimaries, CVImageBuffer.ColorPrimaries_SMPTE_C); break; case VTColorPrimaries.P22: SetStringValue (VTPixelTransferPropertyKeys.DestinationColorPrimaries, CVImageBuffer.ColorPrimaries_P22); break; default: SetStringValue (VTPixelTransferPropertyKeys.DestinationColorPrimaries, null); break; } } } #if NET [SupportedOSPlatform ("ios10.0")] [SupportedOSPlatform ("tvos10.2")] [SupportedOSPlatform ("maccatalyst")] [SupportedOSPlatform ("macos")] #else [iOS (10,0)] #endif public VTTransferFunction DestinationTransferFunction { get { var key = GetNSStringValue (VTPixelTransferPropertyKeys.DestinationTransferFunction); if (key == null) return VTTransferFunction.Unset; if (key == CVImageBuffer.TransferFunction_ITU_R_709_2) return VTTransferFunction.ItuR7092; if (key == CVImageBuffer.TransferFunction_SMPTE_240M_1995) return VTTransferFunction.Smpte240M1955; if (key == CVImageBuffer.TransferFunction_UseGamma) return VTTransferFunction.UseGamma; return VTTransferFunction.Unset; } set { switch (value) { case VTTransferFunction.ItuR7092: SetStringValue (VTPixelTransferPropertyKeys.DestinationTransferFunction, CVImageBuffer.TransferFunction_ITU_R_709_2); break; case VTTransferFunction.Smpte240M1955: SetStringValue (VTPixelTransferPropertyKeys.DestinationTransferFunction, CVImageBuffer.TransferFunction_SMPTE_240M_1995); break; case VTTransferFunction.UseGamma: SetStringValue (VTPixelTransferPropertyKeys.DestinationTransferFunction, CVImageBuffer.TransferFunction_UseGamma); break; default: SetStringValue (VTPixelTransferPropertyKeys.DestinationTransferFunction, null); break; } } } public VTYCbCrMatrix DestinationYCbCrMatrix { get { var key = GetNSStringValue (VTPixelTransferPropertyKeys.DestinationYCbCrMatrix); if (key == null) return VTYCbCrMatrix.Unset; if (key == CVImageBuffer.YCbCrMatrix_ITU_R_709_2) return VTYCbCrMatrix.ItuR7092; if (key == CVImageBuffer.YCbCrMatrix_ITU_R_601_4) return VTYCbCrMatrix.ItuR6014; if (key == CVImageBuffer.YCbCrMatrix_SMPTE_240M_1995) return VTYCbCrMatrix.Smpte240M1955; return VTYCbCrMatrix.Unset; } set { switch (value) { case VTYCbCrMatrix.ItuR7092: SetStringValue (VTPixelTransferPropertyKeys.DestinationYCbCrMatrix, CVImageBuffer.YCbCrMatrix_ITU_R_709_2); break; case VTYCbCrMatrix.ItuR6014: SetStringValue (VTPixelTransferPropertyKeys.DestinationYCbCrMatrix, CVImageBuffer.YCbCrMatrix_ITU_R_601_4); break; case VTYCbCrMatrix.Smpte240M1955: SetStringValue (VTPixelTransferPropertyKeys.DestinationYCbCrMatrix, CVImageBuffer.YCbCrMatrix_SMPTE_240M_1995); break; default: SetStringValue (VTPixelTransferPropertyKeys.DestinationYCbCrMatrix, null); break; } } } } }
34.863415
129
0.767315
[ "BSD-3-Clause" ]
stephen-hawley/xamarin-macios
src/VideoToolbox/VTPixelTransferProperties.cs
7,147
C#
/******************************************************************************* * Copyright 2012-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"). You may not use * this file except in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * ***************************************************************************** * * AWS Tools for Windows (TM) PowerShell (TM) * */ using System; using System.Collections.Generic; using System.Linq; using System.Management.Automation; using System.Text; using Amazon.PowerShell.Common; using Amazon.Runtime; using Amazon.AlexaForBusiness; using Amazon.AlexaForBusiness.Model; namespace Amazon.PowerShell.Cmdlets.ALXB { /// <summary> /// Creates a skill group with a specified name and description. /// </summary> [Cmdlet("New", "ALXBSkillGroup", SupportsShouldProcess = true, ConfirmImpact = ConfirmImpact.Medium)] [OutputType("System.String")] [AWSCmdlet("Calls the Alexa For Business CreateSkillGroup API operation.", Operation = new[] {"CreateSkillGroup"}, SelectReturnType = typeof(Amazon.AlexaForBusiness.Model.CreateSkillGroupResponse))] [AWSCmdletOutput("System.String or Amazon.AlexaForBusiness.Model.CreateSkillGroupResponse", "This cmdlet returns a System.String object.", "The service call response (type Amazon.AlexaForBusiness.Model.CreateSkillGroupResponse) can also be referenced from properties attached to the cmdlet entry in the $AWSHistory stack." )] public partial class NewALXBSkillGroupCmdlet : AmazonAlexaForBusinessClientCmdlet, IExecutor { #region Parameter ClientRequestToken /// <summary> /// <para> /// <para>A unique, user-specified identifier for this request that ensures idempotency. </para> /// </para> /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public System.String ClientRequestToken { get; set; } #endregion #region Parameter Description /// <summary> /// <para> /// <para>The description for the skill group.</para> /// </para> /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public System.String Description { get; set; } #endregion #region Parameter SkillGroupName /// <summary> /// <para> /// <para>The name for the skill group.</para> /// </para> /// </summary> #if !MODULAR [System.Management.Automation.Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true)] #else [System.Management.Automation.Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true, Mandatory = true)] [System.Management.Automation.AllowEmptyString] [System.Management.Automation.AllowNull] #endif [Amazon.PowerShell.Common.AWSRequiredParameter] public System.String SkillGroupName { get; set; } #endregion #region Parameter Select /// <summary> /// Use the -Select parameter to control the cmdlet output. The default value is 'SkillGroupArn'. /// Specifying -Select '*' will result in the cmdlet returning the whole service response (Amazon.AlexaForBusiness.Model.CreateSkillGroupResponse). /// Specifying the name of a property of type Amazon.AlexaForBusiness.Model.CreateSkillGroupResponse will result in that property being returned. /// Specifying -Select '^ParameterName' will result in the cmdlet returning the selected cmdlet parameter value. /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public string Select { get; set; } = "SkillGroupArn"; #endregion #region Parameter PassThru /// <summary> /// Changes the cmdlet behavior to return the value passed to the SkillGroupName parameter. /// The -PassThru parameter is deprecated, use -Select '^SkillGroupName' instead. This parameter will be removed in a future version. /// </summary> [System.Obsolete("The -PassThru parameter is deprecated, use -Select '^SkillGroupName' instead. This parameter will be removed in a future version.")] [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public SwitchParameter PassThru { get; set; } #endregion #region Parameter Force /// <summary> /// This parameter overrides confirmation prompts to force /// the cmdlet to continue its operation. This parameter should always /// be used with caution. /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public SwitchParameter Force { get; set; } #endregion protected override void ProcessRecord() { base.ProcessRecord(); var resourceIdentifiersText = FormatParameterValuesForConfirmationMsg(nameof(this.SkillGroupName), MyInvocation.BoundParameters); if (!ConfirmShouldProceed(this.Force.IsPresent, resourceIdentifiersText, "New-ALXBSkillGroup (CreateSkillGroup)")) { return; } var context = new CmdletContext(); // allow for manipulation of parameters prior to loading into context PreExecutionContextLoad(context); #pragma warning disable CS0618, CS0612 //A class member was marked with the Obsolete attribute if (ParameterWasBound(nameof(this.Select))) { context.Select = CreateSelectDelegate<Amazon.AlexaForBusiness.Model.CreateSkillGroupResponse, NewALXBSkillGroupCmdlet>(Select) ?? throw new System.ArgumentException("Invalid value for -Select parameter.", nameof(this.Select)); if (this.PassThru.IsPresent) { throw new System.ArgumentException("-PassThru cannot be used when -Select is specified.", nameof(this.Select)); } } else if (this.PassThru.IsPresent) { context.Select = (response, cmdlet) => this.SkillGroupName; } #pragma warning restore CS0618, CS0612 //A class member was marked with the Obsolete attribute context.ClientRequestToken = this.ClientRequestToken; context.Description = this.Description; context.SkillGroupName = this.SkillGroupName; #if MODULAR if (this.SkillGroupName == null && ParameterWasBound(nameof(this.SkillGroupName))) { WriteWarning("You are passing $null as a value for parameter SkillGroupName which is marked as required. In case you believe this parameter was incorrectly marked as required, report this by opening an issue at https://github.com/aws/aws-tools-for-powershell/issues."); } #endif // allow further manipulation of loaded context prior to processing PostExecutionContextLoad(context); var output = Execute(context) as CmdletOutput; ProcessOutput(output); } #region IExecutor Members public object Execute(ExecutorContext context) { var cmdletContext = context as CmdletContext; // create request var request = new Amazon.AlexaForBusiness.Model.CreateSkillGroupRequest(); if (cmdletContext.ClientRequestToken != null) { request.ClientRequestToken = cmdletContext.ClientRequestToken; } if (cmdletContext.Description != null) { request.Description = cmdletContext.Description; } if (cmdletContext.SkillGroupName != null) { request.SkillGroupName = cmdletContext.SkillGroupName; } CmdletOutput output; // issue call var client = Client ?? CreateClient(_CurrentCredentials, _RegionEndpoint); try { var response = CallAWSServiceOperation(client, request); object pipelineOutput = null; pipelineOutput = cmdletContext.Select(response, this); output = new CmdletOutput { PipelineOutput = pipelineOutput, ServiceResponse = response }; } catch (Exception e) { output = new CmdletOutput { ErrorResponse = e }; } return output; } public ExecutorContext CreateContext() { return new CmdletContext(); } #endregion #region AWS Service Operation Call private Amazon.AlexaForBusiness.Model.CreateSkillGroupResponse CallAWSServiceOperation(IAmazonAlexaForBusiness client, Amazon.AlexaForBusiness.Model.CreateSkillGroupRequest request) { Utils.Common.WriteVerboseEndpointMessage(this, client.Config, "Alexa For Business", "CreateSkillGroup"); try { #if DESKTOP return client.CreateSkillGroup(request); #elif CORECLR return client.CreateSkillGroupAsync(request).GetAwaiter().GetResult(); #else #error "Unknown build edition" #endif } catch (AmazonServiceException exc) { var webException = exc.InnerException as System.Net.WebException; if (webException != null) { throw new Exception(Utils.Common.FormatNameResolutionFailureMessage(client.Config, webException.Message), webException); } throw; } } #endregion internal partial class CmdletContext : ExecutorContext { public System.String ClientRequestToken { get; set; } public System.String Description { get; set; } public System.String SkillGroupName { get; set; } public System.Func<Amazon.AlexaForBusiness.Model.CreateSkillGroupResponse, NewALXBSkillGroupCmdlet, object> Select { get; set; } = (response, cmdlet) => response.SkillGroupArn; } } }
45.056452
285
0.615268
[ "Apache-2.0" ]
5u5hma/aws-tools-for-powershell
modules/AWSPowerShell/Cmdlets/AlexaForBusiness/Basic/New-ALXBSkillGroup-Cmdlet.cs
11,174
C#
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using Microsoft.Kubernetes.Controller.Rate; using Yarp.Kubernetes.OperatorFramework.Fakes; using System; using Xunit; namespace Yarp.Kubernetes.OperatorFramework.Rate; public class ReservationTests { [Fact] public void NotOkayAlwaysReturnsMaxValueDelay() { var clock = new FakeSystemClock(); var reservation = new Reservation( clock: clock, limiter: default, ok: false); var delay1 = reservation.Delay(); var delayFrom1 = reservation.DelayFrom(clock.UtcNow); clock.Advance(TimeSpan.FromMinutes(3)); var delay2 = reservation.Delay(); var delayFrom2 = reservation.DelayFrom(clock.UtcNow); Assert.Equal(TimeSpan.MaxValue, delay1); Assert.Equal(TimeSpan.MaxValue, delayFrom1); Assert.Equal(TimeSpan.MaxValue, delay2); Assert.Equal(TimeSpan.MaxValue, delayFrom2); } [Fact] public void DelayIsZeroWhenTimeToActIsNowOrEarlier() { var clock = new FakeSystemClock(); var reservation = new Reservation( clock: clock, limiter: default, ok: true, timeToAct: clock.UtcNow, limit: default); var delay1 = reservation.Delay(); var delayFrom1 = reservation.DelayFrom(clock.UtcNow); clock.Advance(TimeSpan.FromMinutes(3)); var delay2 = reservation.Delay(); var delayFrom2 = reservation.DelayFrom(clock.UtcNow); Assert.Equal(TimeSpan.Zero, delay1); Assert.Equal(TimeSpan.Zero, delayFrom1); Assert.Equal(TimeSpan.Zero, delay2); Assert.Equal(TimeSpan.Zero, delayFrom2); } [Fact] public void DelayGetsSmallerAsTimePasses() { var clock = new FakeSystemClock(); var reservation = new Reservation( clock: clock, limiter: default, ok: true, timeToAct: clock.UtcNow.Add(TimeSpan.FromMinutes(5)), limit: default); var delay1 = reservation.Delay(); clock.Advance(TimeSpan.FromMinutes(3)); var delay2 = reservation.Delay(); clock.Advance(TimeSpan.FromMinutes(3)); var delay3 = reservation.Delay(); Assert.Equal(TimeSpan.FromMinutes(5), delay1); Assert.Equal(TimeSpan.FromMinutes(2), delay2); Assert.Equal(TimeSpan.Zero, delay3); } [Fact] public void DelayFromNotChangedByTimePassing() { var clock = new FakeSystemClock(); var reservation = new Reservation( clock: clock, limiter: default, ok: true, timeToAct: clock.UtcNow.Add(TimeSpan.FromMinutes(5)), limit: default); var twoMinutesPast = clock.UtcNow.Subtract(TimeSpan.FromMinutes(2)); var twoMinutesFuture = clock.UtcNow.Add(TimeSpan.FromMinutes(2)); var delay1 = reservation.DelayFrom(clock.UtcNow); var delayPast1 = reservation.DelayFrom(twoMinutesPast); var delayFuture1 = reservation.DelayFrom(twoMinutesFuture); clock.Advance(TimeSpan.FromMinutes(3)); var delay2 = reservation.DelayFrom(clock.UtcNow); var delayPast2 = reservation.DelayFrom(twoMinutesPast); var delayFuture2 = reservation.DelayFrom(twoMinutesFuture); Assert.Equal(TimeSpan.FromMinutes(5), delay1); Assert.Equal(TimeSpan.FromMinutes(7), delayPast1); Assert.Equal(TimeSpan.FromMinutes(3), delayFuture1); Assert.Equal(TimeSpan.FromMinutes(2), delay2); Assert.Equal(TimeSpan.FromMinutes(7), delayPast2); Assert.Equal(TimeSpan.FromMinutes(3), delayFuture2); } }
34.082569
76
0.645491
[ "MIT" ]
Xen0byte/reverse-proxy
test/Kubernetes.Tests/OperatorFramework/Rate/ReservationTests.cs
3,715
C#
using System.Windows; namespace pdfjoiner.DesktopClient { /// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App : Application { } }
16.083333
42
0.626943
[ "MIT" ]
harrystb/pdfjoiner
pdfjoiner.DesktopClient/App.xaml.cs
195
C#
 namespace lab_10 { partial class Form1 { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.Windows.Forms.DataVisualization.Charting.ChartArea chartArea1 = new System.Windows.Forms.DataVisualization.Charting.ChartArea(); System.Windows.Forms.DataVisualization.Charting.Legend legend1 = new System.Windows.Forms.DataVisualization.Charting.Legend(); this.chart1 = new System.Windows.Forms.DataVisualization.Charting.Chart(); this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel(); this.flowLayoutPanel1 = new System.Windows.Forms.FlowLayoutPanel(); this.buttonAdd = new System.Windows.Forms.Button(); ((System.ComponentModel.ISupportInitialize)(this.chart1)).BeginInit(); this.tableLayoutPanel1.SuspendLayout(); this.flowLayoutPanel1.SuspendLayout(); this.SuspendLayout(); // // chart1 // chartArea1.Name = "ChartArea1"; this.chart1.ChartAreas.Add(chartArea1); this.chart1.Dock = System.Windows.Forms.DockStyle.Fill; legend1.Name = "Legend1"; this.chart1.Legends.Add(legend1); this.chart1.Location = new System.Drawing.Point(203, 3); this.chart1.Name = "chart1"; this.chart1.Size = new System.Drawing.Size(1092, 681); this.chart1.TabIndex = 0; this.chart1.Text = "chart1"; // // tableLayoutPanel1 // this.tableLayoutPanel1.ColumnCount = 2; this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 200F)); this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F)); this.tableLayoutPanel1.Controls.Add(this.chart1, 1, 0); this.tableLayoutPanel1.Controls.Add(this.flowLayoutPanel1, 0, 0); this.tableLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Fill; this.tableLayoutPanel1.Location = new System.Drawing.Point(0, 0); this.tableLayoutPanel1.Name = "tableLayoutPanel1"; this.tableLayoutPanel1.RowCount = 1; this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F)); this.tableLayoutPanel1.Size = new System.Drawing.Size(1298, 687); this.tableLayoutPanel1.TabIndex = 1; // // flowLayoutPanel1 // this.flowLayoutPanel1.Controls.Add(this.buttonAdd); this.flowLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Fill; this.flowLayoutPanel1.Location = new System.Drawing.Point(3, 3); this.flowLayoutPanel1.Name = "flowLayoutPanel1"; this.flowLayoutPanel1.Size = new System.Drawing.Size(194, 681); this.flowLayoutPanel1.TabIndex = 1; // // buttonAdd // this.buttonAdd.Location = new System.Drawing.Point(3, 3); this.buttonAdd.Name = "buttonAdd"; this.buttonAdd.Size = new System.Drawing.Size(191, 23); this.buttonAdd.TabIndex = 2; this.buttonAdd.Text = "Add chart"; this.buttonAdd.UseVisualStyleBackColor = true; this.buttonAdd.Click += new System.EventHandler(this.buttonAdd_Click); // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(1298, 687); this.Controls.Add(this.tableLayoutPanel1); this.Name = "Form1"; this.Text = "Form1"; ((System.ComponentModel.ISupportInitialize)(this.chart1)).EndInit(); this.tableLayoutPanel1.ResumeLayout(false); this.flowLayoutPanel1.ResumeLayout(false); this.ResumeLayout(false); } #endregion private System.Windows.Forms.DataVisualization.Charting.Chart chart1; private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1; private System.Windows.Forms.FlowLayoutPanel flowLayoutPanel1; private System.Windows.Forms.Button buttonAdd; } }
45.885965
147
0.619002
[ "MIT" ]
kpagacz/software-engineering
programowanie-komponentowe/lab-10/Form1.Designer.cs
5,233
C#
using System; using System.Linq; using System.Threading.Tasks; using CommunityBot.Extensions; using CommunityBot.Features.GlobalAccounts; using CommunityBot.Providers; using Discord; using Discord.Commands; namespace CommunityBot.Modules.RoleAssignments { [Group("RoleByPhrase"), Alias("rbp"), Summary("Settings for auto-assigning roles based on a sent Phrase")] [RequireUserPermission(GuildPermission.Administrator)] public class RoleByPhrase : ModuleBase<MiunieCommandContext> { [Command("status"), Alias("s"), RequireUserPermission(GuildPermission.Administrator)] [Remarks("Returns the current state of RoleByPhrase lists and relations.")] public async Task RbpStatus() { var rbp = GlobalGuildAccounts.GetGuildAccount(Context.Guild).RoleByPhraseSettings; var phrases = rbp.Phrases.Any() ? string.Join("\n", rbp.Phrases.Select(p => $"({rbp.Phrases.IndexOf(p)}) - {p}")) : "No phrases stored\nAdd one with `rbp addPhrase YOUR-PHRASE`"; var roles = rbp.RolesIds.Any() ? string.Join("\n", rbp.RolesIds.Select(r => $"({rbp.RolesIds.IndexOf(r)}) - {Context.Guild.GetRole(r).Name}")) : "No roles stored\nAdd one with `rbp addRole @SomeRole`"; var relations = rbp.Relations.Any() ? string.Join("\n", rbp.Relations.Select(r => $"Phrase {r.PhraseIndex} => Role {r.RoleIdIndex}")) : "No relations created\nAdd one with `rbp addRelation PHRASE-ID ROLE-ID`"; var embed = new EmbedBuilder(); embed.WithTitle($"Role Assignments for {Context.Guild.Name}"); embed.AddField("Phrases", phrases); embed.AddField("Roles", roles); embed.AddField("Relations", relations); await Context.Channel.SendMessageAsync("", embed: embed.Build()); } [Command("addPhrase"), Alias("ap"), RequireUserPermission(GuildPermission.Administrator)] [Remarks("Adds a new phrase to the guild's settings. (Phrase is a Remainder, so no double quotes are needed)")] public async Task RbpAddPhrase([Remainder]string phrase) { var result = RoleByPhraseProvider.AddPhrase(Context.Guild, phrase); if (result == RoleByPhraseProvider.RoleByPhraseOperationResult.Success) { await RbpStatus(); } else { await ReplyAsync("Something went wrong..."); Console.WriteLine(result.ToString()); } } [Command("addRole"), Alias("arole"), RequireUserPermission(GuildPermission.Administrator)] [Remarks("Adds a new phrase to the guild's settings. (Phrase is a Remainder, so no double quotes are needed)")] public async Task RbpAddRole(IRole role) { var result = RoleByPhraseProvider.AddRole(Context.Guild, role); if (result == RoleByPhraseProvider.RoleByPhraseOperationResult.Success) { await RbpStatus(); } else { await ReplyAsync("Something went wrong..."); Console.WriteLine(result.ToString()); } } [Command("addRelation"), Alias("arel"), RequireUserPermission(GuildPermission.Administrator)] [Remarks("Adds a new relation between a phrase and a role. Relation are automatically enabled and used after you add them.")] public async Task RbpAddRelation(int phraseIndex, int roleIndex) { var result = RoleByPhraseProvider.CreateRelation(Context.Guild, phraseIndex, roleIndex); if (result == RoleByPhraseProvider.RelationCreationResult.Success) { await RbpStatus(); } else { await ReplyAsync("Something went wrong..."); Console.WriteLine(result.ToString()); } } [Command("removeRelation"), Alias("rrel"), RequireUserPermission(GuildPermission.Administrator)] [Remarks("Removes a relation between a phrase and a role.")] public async Task RbpRemoveRelation(int phraseIndex, int roleIndex) { RoleByPhraseProvider.RemoveRelation(Context.Guild, phraseIndex, roleIndex); await RbpStatus(); } [Command("removePhrase"), Alias("rp"), RequireUserPermission(GuildPermission.Administrator)] [Remarks("Removes a phrase and its relations.")] public async Task RbpRemovePhrase(int phraseIndex) { RoleByPhraseProvider.RemovePhrase(Context.Guild, phraseIndex); await RbpStatus(); } [Command("removeRole"), Alias("rrole"), RequireUserPermission(GuildPermission.Administrator)] [Remarks("Removes a role and its relations.")] public async Task RbpRemoveRole(int roleIndex) { RoleByPhraseProvider.RemoveRole(Context.Guild, roleIndex); await RbpStatus(); } } }
45.236364
221
0.634445
[ "MIT" ]
codacy-badger/Community-Discord-BOT
CommunityBot/Modules/RoleAssignments/RoleByPhrase.cs
4,978
C#
using System.Collections.Generic; namespace MailChimp.Api.Net.Domain.Reports { public class UrlsClicked { public string id { get; set; } public string url { get; set; } public int total_clicks { get; set; } public double click_percentage { get; set; } public int unique_clicks { get; set; } public double unique_click_percentage { get; set; } public string last_click { get; set; } public string campaign_id { get; set; } public List<Link> _links { get; set; } } }
30.611111
59
0.62069
[ "MIT" ]
kinamarie016/MailChimp.Api.Net-master
MailChimp.Api.Net/Domain/Reports/UrlsClicked.cs
553
C#
using System; namespace Wpf.Home { public class SampleVm { private static int _idCount; public SampleVm() { Id = _idCount++; Tags = string.Empty; } public SampleVm(string title, Type content, string tags = "") { Id = _idCount++; Title = title; Content = content; Tags = tags; } public int Id { get; private set; } public string Title { get; set; } public Type Content { get; set; } public string Tags { get; set; } } }
21.214286
69
0.486532
[ "MIT" ]
A36664-joingame/LiveCharts
Examples/Wpf/Home/SampleVm.cs
594
C#
// Copyright © .NET Foundation and Contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace PInvoke { using System; using System.Runtime.InteropServices; /// <content> /// The <see cref="SafeAlgorithmHandle"/> nested type. /// </content> public static partial class BCrypt { /// <summary> /// A BCrypt algorithm handle. /// </summary> public class SafeAlgorithmHandle : SafeHandle { /// <summary> /// A handle that may be used in place of <see cref="IntPtr.Zero"/>. /// </summary> public static readonly SafeAlgorithmHandle Null = new SafeAlgorithmHandle(); /// <summary> /// Initializes a new instance of the <see cref="SafeAlgorithmHandle"/> class. /// </summary> public SafeAlgorithmHandle() : base(IntPtr.Zero, true) { } /// <summary> /// Initializes a new instance of the <see cref="SafeAlgorithmHandle"/> class. /// </summary> /// <param name="preexistingHandle">An object that represents the pre-existing handle to use.</param> /// <param name="ownsHandle"> /// <see langword="true" /> to have the native handle released when this safe handle is disposed or finalized; /// <see langword="false" /> otherwise. /// </param> public SafeAlgorithmHandle(IntPtr preexistingHandle, bool ownsHandle = true) : base(IntPtr.Zero, ownsHandle) { this.SetHandle(preexistingHandle); } /// <inheritdoc /> public override bool IsInvalid => this.handle == IntPtr.Zero; /// <inheritdoc /> protected override bool ReleaseHandle() { return BCryptCloseAlgorithmProvider(this.handle, 0) == NTSTATUS.Code.STATUS_SUCCESS; } } } }
36.578947
126
0.561151
[ "MIT" ]
AArnott/pinvoke
src/BCrypt/BCrypt+SafeAlgorithmHandle.cs
2,088
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerStats : MonoBehaviour { [Header("Health")] public int _totalPlayerHealth = 100; public int _currentPlayerHealth = 0; [Header("Mana")] public int _totalPlayerMana = 200; public int _currentPlayerMana = 0; [Header("Script")] [SerializeField] PlayerHUD _hud = null; private void Awake() { _currentPlayerHealth = _totalPlayerHealth; _currentPlayerMana = _totalPlayerMana; } public void DamagePlayer(int damage) { _currentPlayerHealth -= damage; _hud.UpdateStats(); if (_currentPlayerHealth <= 0) { Debug.Log("Died"); } } public void UseMana(int usage) { _currentPlayerMana -= usage; _hud.UpdateStats(); } }
20.52381
50
0.62761
[ "MIT" ]
whroberts/MechanicRecreation_Dishonored
Assets/Scripts/Scripts/PlayerStats.cs
864
C#
using System; using System.Threading; using System.Threading.Tasks; namespace Borg.Infra { public sealed class AsyncLock { private readonly Task<IDisposable> _releaser; private readonly SemaphoreSlim _semaphore = new SemaphoreSlim(1, 1); public AsyncLock() { _releaser = Task.FromResult((IDisposable)new Releaser(this)); } public Task<IDisposable> LockAsync() { var wait = _semaphore.WaitAsync(); return wait.IsCompleted ? _releaser : wait.ContinueWith((_, state) => (IDisposable)state, _releaser.Result, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); } private sealed class Releaser : IDisposable { private readonly AsyncLock m_toRelease; internal Releaser(AsyncLock toRelease) { m_toRelease = toRelease; } public void Dispose() { m_toRelease._semaphore.Release(); } } } }
27.404762
89
0.567333
[ "MIT" ]
mitsbits/NoBorg
src/infra/Borg.Infra/AsyncLock.cs
1,153
C#
using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using SnackHouse.Models.ViewModels; using SnackHouse.Repositories; namespace SnackHouse.Controllers { public class HomeController : Controller { private readonly ILogger<HomeController> _logger; private readonly ISnackRepository _snackRepository; public HomeController(ILogger<HomeController> logger, ISnackRepository snackRepository) { _logger = logger; _snackRepository = snackRepository; } public ActionResult Index() { var homeViewModel = new HomeViewModel { PreferSnacks = _snackRepository.PreferSnacks() }; return View(homeViewModel); } public ActionResult AccessDenied() { return View(); } } }
25.705882
95
0.630435
[ "MIT" ]
karolinagb/SnackHouse
SnackHouse/SnackHouse/Controllers/HomeController.cs
876
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Threading; namespace LegionCalculator { public partial class Form1 : Form { /* * Author Details: * Andrew Hart (Qark on FFG forums) * 31 Oct 2018 */ /* * READ-ME * a-olson * Added support for Observation tokens * see lines 65, 86, 116, 137, 372-405 * 13 Dec 2020 */ public Form1() { InitializeComponent(); } #region Inputs and Constants //Dice int iRedAttack, iBlackAttack, iWhiteAttack; bool bRedDefence, bWhiteDefence; //Attack Keywords int iRam, iImpact, iPierce, iPrecise; //Surges bool bSurgeToCrit, bSurgeToHit, bSurgeToBlock; int iCritical, iAttackerSurgeTokens, iDefenderSurgeTokens; //Tokens bool bDeflect; int iDodgeTokens, iShieldTokens, iObvTokens, iAimTokens; //Cover bool bHeavyCover, bLightCover, bArmour; int iArmourX; //Defence bool Impervious; int UncannyLuck; int iDangerSense; //System int iItterations; static int iMaxDamage = 25; int iArrayConstruction = iMaxDamage + 1; static string sTabs = "\t\t"; int iRerolls; int iRerollsObv; #endregion void GetInfo()//Gets all the input data { //Dice iRedAttack = (int)updnRedAttack.Value; iBlackAttack = (int)updnBlackAttack.Value; iWhiteAttack = (int)updnWhiteAttack.Value; bRedDefence = rbtnRedDefence.Checked; bWhiteDefence = rbtnWhiteDefence.Checked; //Attack Keywords iImpact = (int)updnImpact.Value; iPierce = (int)updnPierce.Value; iPrecise = (int)updnPrecise.Value; //Aim token allows for 2 rerolls automattically. iRam = (int)updnRam.Value; //Surges bSurgeToCrit = rbtnSurgeToCrit.Checked; bSurgeToHit = rbtnSurgeToHits.Checked; bSurgeToBlock = ckbxSurgeToBlock.Checked; iCritical = (int)updnCritical.Value; iAttackerSurgeTokens = (int)updnAttackerSurgeTokens.Value; iDefenderSurgeTokens = (int)updnDefenceSurgeTokens.Value; //Tokens iObvTokens = (int)UpDnObvToken.Value; iAimTokens = (int)UpDnAimToken.Value; iDodgeTokens = (int)UpDnDodgeToken.Value; iShieldTokens = (int)updnShield.Value; //Cover bHeavyCover = rbtnHeavyCover.Checked; bLightCover = rbtnLightCover.Checked; bArmour = ckbxArmour.Checked; iArmourX = (int)UpDnArmourX.Value; //Deflect bDeflect = ckbxDeflect.Checked; if(bDeflect && iDodgeTokens > 0) { bSurgeToBlock = true; } //Defence UncannyLuck = (int)updnLuck.Value; iDangerSense = (int)UpDnDangerSense.Value; Impervious = ckbxImpervious.Checked; //System iRerollsObv = 1; iRerolls = (2 + iPrecise); iItterations = (int)updnItterations.Value; } void RollAndConvertAttack(ref Dice die, ref int critical_used, ref int surge_tokens_used)//Rolls attack die and converts surges where appropriate { die.Roll(); if (die.ReadResult() == "Surge") { if (bSurgeToCrit) { die.Set("Crit"); } else if (critical_used < iCritical) { die.Set("Crit"); critical_used++; } else if (bSurgeToHit) { die.Set("Hit"); } else if (surge_tokens_used < iAttackerSurgeTokens) { die.Set("Hit"); surge_tokens_used++; } else { die.Set("Blank"); } } } void RollAndConvertDefence(ref Dice die, ref int surge_tokens_used)//Rolls defence die and converts surges where appropriate { die.Roll(); if(die.ReadResult() == "Surge") { if (bSurgeToBlock) { die.Set("Block"); } else if (surge_tokens_used < iDefenderSurgeTokens) { die.Set("Block"); surge_tokens_used++; } else { die.Set("Blank"); } } } double FindMedian (int[] damage) { List<int> DamageValues = new List<int>(); for(int i = 0; i <= iMaxDamage; i++) { for (int j = 0; j < damage[i]; j++) { DamageValues.Add(i); } }//Populate List int[] DamageValuesArray = DamageValues.ToArray(); Array.Sort(DamageValuesArray); if(DamageValuesArray.Length == 0) { return 0; } else if (DamageValuesArray.Length % 2 == 0) { //Count is even int a = DamageValuesArray[DamageValuesArray.Length / 2 - 1]; int b = DamageValuesArray[DamageValuesArray.Length / 2]; return (double)(a + b) / (double)2; } else { return DamageValuesArray[DamageValuesArray.Length / 2]; } } double StandardDeviation(int[] damage) { List<int> DamageValues = new List<int>(); for (int i = 0; i <= iMaxDamage; i++) { for (int j = 0; j < damage[i]; j++) { DamageValues.Add(i); } }//Populate List int[] values = DamageValues.ToArray(); double avg = values.Average(); return Math.Sqrt(values.Average(v => Math.Pow(v - avg, 2))); } void Output(int[] damage) //Creates the outout string and sets the output textbox's text. { string Output = "# Hits" + sTabs + "Probability (%)\n"; int ModeValue = 0; double ModeProbability = 0; for (int i = 0; i <= iMaxDamage; i++) { double Probability = (double)damage[i] / (double)iItterations * (double)100; if(Probability > ModeProbability) { ModeValue = i; ModeProbability = Probability; } Output += i + sTabs + Probability + "\n"; } Output += "\nAt Least" + sTabs + "Probability (%)\n"; for (int i = iMaxDamage; i >= 0; i--) { double Probability = 0; for (int j = i; j <= iMaxDamage; j++) { Probability += (double)damage[j] / (double)iItterations * (double)100; } Output += i + sTabs + Probability + "\n"; } #region A M SD double Average = 0; double Median = 0; double StandardD = 0; //Find Average for (int i = 0; i <= iMaxDamage; i++) { Average += damage[i] * i; } Average /= (double)iItterations; Output += "\nAverage: " + Average + "\n"; //Find Median Median = FindMedian(damage); Output += "Median: " + Median + "\n"; //Mode Output += "Mode: " + ModeValue + "\n"; //find SD StandardD = StandardDeviation(damage); Output += "Standard Deviation: " + StandardD + "\n"; #endregion rtxtbxOutput.Text = Output; } #region Events private void btnSimulate_Click(object sender, EventArgs e) { GetInfo(); int[] Damage = new int[iArrayConstruction]; for (int i = 1; i <= iItterations; i++) { probarCompletion.Value = (int)((double)i / (double)iItterations * (double)100); int RolledHits = 0; int RolledCrits = 0; int RolledBlocks = 0; #region Attack Dice Generation Step 1 List<Dice> ListOfAttackDice = new List<Dice>(); for (int j = 0; j < iRedAttack; j++) { Dice Die = new Dice("RedAttack"); ListOfAttackDice.Add(Die); } for (int j = 0; j < iBlackAttack; j++) { Dice Die = new Dice("BlackAttack"); ListOfAttackDice.Add(Die); } for (int j = 0; j < iWhiteAttack; j++) { Dice Die = new Dice("WhiteAttack"); ListOfAttackDice.Add(Die); } #endregion #region Attack Step 4 int CriticalUsed = 0; int SurgeTokensUsed = 0; int RamUsed = 0; //Roll attack pool foreach (Dice AttackDie in ListOfAttackDice) { Dice Die = AttackDie; RollAndConvertAttack(ref Die, ref CriticalUsed, ref SurgeTokensUsed); } //Spend Aim Tokens for(int aim_count = 0; aim_count < iAimTokens; aim_count++) { int RerolledDice = 0; foreach (Dice AttackDie in ListOfAttackDice) { if (RerolledDice < iRerolls && AttackDie.ReadResult() == "Blank" && AttackDie.ReadColour() == "RedAttack") { Dice Die = AttackDie; RollAndConvertAttack(ref Die, ref CriticalUsed, ref SurgeTokensUsed); RerolledDice++; } }//Red foreach (Dice AttackDie in ListOfAttackDice) { if (RerolledDice < iRerolls && AttackDie.ReadResult() == "Blank" && AttackDie.ReadColour() == "BlackAttack") { Dice Die = AttackDie; RollAndConvertAttack(ref Die, ref CriticalUsed, ref SurgeTokensUsed); RerolledDice++; } }//Black foreach (Dice AttackDie in ListOfAttackDice) { if (RerolledDice < iRerolls && AttackDie.ReadResult() == "Blank" && AttackDie.ReadColour() == "WhiteAttack") { Dice Die = AttackDie; RollAndConvertAttack(ref Die, ref CriticalUsed, ref SurgeTokensUsed); RerolledDice++; } }//White } //Spend Observation Tokens for(int obv_count = 0; obv_count < iObvTokens; obv_count++) { int RerolledDice = 0; foreach (Dice AttackDie in ListOfAttackDice) { if (RerolledDice < iRerollsObv && AttackDie.ReadResult() == "Blank" && AttackDie.ReadColour() == "RedAttack") { Dice Die = AttackDie; RollAndConvertAttack(ref Die, ref CriticalUsed, ref SurgeTokensUsed); RerolledDice++; } }//Red foreach (Dice AttackDie in ListOfAttackDice) { if (RerolledDice < iRerollsObv && AttackDie.ReadResult() == "Blank" && AttackDie.ReadColour() == "BlackAttack") { Dice Die = AttackDie; RollAndConvertAttack(ref Die, ref CriticalUsed, ref SurgeTokensUsed); RerolledDice++; } }//Black foreach (Dice AttackDie in ListOfAttackDice) { if (RerolledDice < iRerollsObv && AttackDie.ReadResult() == "Blank" && AttackDie.ReadColour() == "WhiteAttack") { Dice Die = AttackDie; RollAndConvertAttack(ref Die, ref CriticalUsed, ref SurgeTokensUsed); RerolledDice++; } }//White } //Ram! foreach(Dice AttackDie in ListOfAttackDice) { if(RamUsed < iRam) { if (AttackDie.ReadResult() == "Blank") { AttackDie.Set("Crit"); RamUsed++; } } } foreach (Dice AttackDie in ListOfAttackDice) { if (RamUsed < iRam) { if (AttackDie.ReadResult() == "Hit") { AttackDie.Set("Crit"); RamUsed++; } } } //Tally Results foreach (Dice AttackDie in ListOfAttackDice) { if (AttackDie.ReadResult() == "Crit") { RolledCrits++; } else if (AttackDie.ReadResult() == "Hit") { RolledHits++; } } #endregion #region Modifications Step 5 //Apply Cover if (bLightCover) { RolledHits -= 1; } else if (bHeavyCover) { RolledHits -= 2; } //Apply Dodge RolledHits -= iDodgeTokens; //Safety Checks if (RolledHits < 0) { RolledHits = 0; } if (RolledCrits < 0) { RolledCrits = 0; } //Don't think this can actually occur //Convert for Armour and Impact if (bArmour) { if (RolledHits >= iImpact) { RolledCrits += iImpact; } else { RolledCrits += RolledHits; } RolledHits = 0; } else //Armour X { if (RolledHits >= iImpact) { RolledCrits += iImpact; RolledHits -= iImpact; RolledHits -= iArmourX; if (RolledHits < 0) { RolledHits = 0; } //Safety Check } else { RolledCrits += RolledHits; RolledHits = 0; } } #endregion #region Defence Dice Generation Step 7 int TotalDefenceDice = RolledCrits + RolledHits + iDangerSense; TotalDefenceDice -= iShieldTokens; //Roll less dice for the shields you use. The blocks are added later, in step 8. if(TotalDefenceDice < 0) { TotalDefenceDice = 0; } if (Impervious) { TotalDefenceDice += iPierce; } List<Dice> ListOfDefenceDice = new List<Dice>(); for (int j = 0; j < TotalDefenceDice; j++) { if (bRedDefence) { Dice Die = new Dice("RedDefence"); ListOfDefenceDice.Add(Die); } else if (bWhiteDefence) { Dice Die = new Dice("WhiteDefence"); ListOfDefenceDice.Add(Die); } } #endregion #region Defend Step 7 int DefenderSurgeTokensUsed = 0; //Roll defence pool foreach (Dice DefenceDie in ListOfDefenceDice) { Dice Die = DefenceDie; RollAndConvertDefence(ref Die, ref DefenderSurgeTokensUsed); } //Luck if(UncannyLuck > 0) { int RerolledDice = 0; foreach (Dice DefenceDie in ListOfDefenceDice) { if(RerolledDice < UncannyLuck && DefenceDie.ReadResult() == "Blank") { Dice Die = DefenceDie; RollAndConvertDefence(ref Die, ref DefenderSurgeTokensUsed); } } } foreach (Dice DefenceDie in ListOfDefenceDice) { if (DefenceDie.ReadResult() == "Block") { RolledBlocks++; } } #endregion #region Modifications Step 8 //Pierce RolledBlocks -= iPierce; if (RolledBlocks < 0) { RolledBlocks = 0; } //Shields RolledBlocks += iShieldTokens; #endregion #region Compare Results Step 9 try { int DamageAmount = RolledHits + RolledCrits - RolledBlocks; if(DamageAmount < 0) { DamageAmount = 0; } Damage[DamageAmount]++; } catch { MessageBox.Show("Error: Too much damage. Please decrease number of attack dice.", "Error!"); break; } #endregion }; Output(Damage); } private void rbtnSurgeToCrit_CheckedChanged(object sender, EventArgs e) { //not used } private void rbtnSurgeToHits_CheckedChanged(object sender, EventArgs e) { //not used } private void rbtnSurgesNone_CheckedChanged(object sender, EventArgs e) { //not used } private void updnAttackerSurgeTokens_ValueChanged(object sender, EventArgs e) { //not used } #endregion } class Dice { private string sResult; private string sColour; static private string sHit = "Hit", sCrit = "Crit", sSurge = "Surge", sBlock = "Block", sBlank = "Blank"; private static string[] sRedAttack = { sHit, sHit, sHit, sHit, sHit, sCrit, sSurge, sBlank }, sBlackAttack = { sHit, sHit, sHit, sCrit, sSurge, sBlank, sBlank, sBlank }, sWhiteAttack = { sHit, sCrit, sSurge, sBlank, sBlank, sBlank, sBlank, sBlank }, sRedDefence = { sBlock, sBlock, sBlock, sSurge, sBlank, sBlank }, sWhiteDefence = { sBlock, sSurge, sBlank, sBlank, sBlank, sBlank }; public Dice (string colour) { sColour = colour; } public string Roll() { int RollResult; if (sColour == "RedAttack" || sColour == "BlackAttack" || sColour == "WhiteAttack") { RollResult = StaticRandom.Rand(0, 8); } else if(sColour == "RedDefence" || sColour == "WhiteDefence") { RollResult = StaticRandom.Rand(0, 6); } else { sResult = sBlank; return sResult; } if(sColour == "RedAttack") { sResult = sRedAttack[RollResult]; } else if(sColour == "BlackAttack") { sResult = sBlackAttack[RollResult]; } else if (sColour == "WhiteAttack") { sResult = sWhiteAttack[RollResult]; } else if (sColour == "RedDefence") { sResult = sRedDefence[RollResult]; } else if (sColour == "WhiteDefence") { sResult = sWhiteDefence[RollResult]; } return sResult; } public void Set(string result) { sResult = result; } #region read public string ReadResult() { return sResult; } public string ReadColour() { return sColour; } #endregion } static class StaticRandom { static int seed = Environment.TickCount; static readonly ThreadLocal<Random> random = new ThreadLocal<Random>(() => new Random(Interlocked.Increment(ref seed))); public static int Rand(int min, int max) { return random.Value.Next(min, max); } } }
34.089443
154
0.416706
[ "MIT" ]
a-olson/SW-Legion-Probability-Calculator
Form1.cs
23,249
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc.Razor.Compilation; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Text; using Microsoft.Extensions.DependencyModel; using DependencyContextCompilationOptions = Microsoft.Extensions.DependencyModel.CompilationOptions; namespace Microsoft.AspNetCore.Mvc.Razor.Internal { public class CSharpCompiler { #pragma warning disable CS0618 // Type or member is obsolete private readonly RazorReferenceManager _referenceManager; #pragma warning restore CS0618 // Type or member is obsolete private readonly IHostingEnvironment _hostingEnvironment; private bool _optionsInitialized; private CSharpParseOptions _parseOptions; private CSharpCompilationOptions _compilationOptions; private EmitOptions _emitOptions; private bool _emitPdb; #pragma warning disable CS0618 // Type or member is obsolete public CSharpCompiler(RazorReferenceManager manager, IHostingEnvironment hostingEnvironment) #pragma warning restore CS0618 // Type or member is obsolete { _referenceManager = manager ?? throw new ArgumentNullException(nameof(manager)); _hostingEnvironment = hostingEnvironment ?? throw new ArgumentNullException(nameof(hostingEnvironment)); } public virtual CSharpParseOptions ParseOptions { get { EnsureOptions(); return _parseOptions; } } public virtual CSharpCompilationOptions CSharpCompilationOptions { get { EnsureOptions(); return _compilationOptions; } } public virtual bool EmitPdb { get { EnsureOptions(); return _emitPdb; } } public virtual EmitOptions EmitOptions { get { EnsureOptions(); return _emitOptions; } } public SyntaxTree CreateSyntaxTree(SourceText sourceText) { return CSharpSyntaxTree.ParseText( sourceText, options: ParseOptions); } public CSharpCompilation CreateCompilation(string assemblyName) { return CSharpCompilation.Create( assemblyName, options: CSharpCompilationOptions, references: _referenceManager.CompilationReferences); } // Internal for unit testing. protected internal virtual DependencyContextCompilationOptions GetDependencyContextCompilationOptions() { if (!string.IsNullOrEmpty(_hostingEnvironment.ApplicationName)) { var applicationAssembly = Assembly.Load(new AssemblyName(_hostingEnvironment.ApplicationName)); var dependencyContext = DependencyContext.Load(applicationAssembly); if (dependencyContext?.CompilationOptions != null) { return dependencyContext.CompilationOptions; } } return DependencyContextCompilationOptions.Default; } private void EnsureOptions() { if (!_optionsInitialized) { var dependencyContextOptions = GetDependencyContextCompilationOptions(); _parseOptions = GetParseOptions(_hostingEnvironment, dependencyContextOptions); _compilationOptions = GetCompilationOptions(_hostingEnvironment, dependencyContextOptions); _emitOptions = GetEmitOptions(dependencyContextOptions); _optionsInitialized = true; } } private EmitOptions GetEmitOptions(DependencyContextCompilationOptions dependencyContextOptions) { // Assume we're always producing pdbs unless DebugType = none _emitPdb = true; DebugInformationFormat debugInformationFormat; if (string.IsNullOrEmpty(dependencyContextOptions.DebugType)) { debugInformationFormat = SymbolsUtility.SupportsFullPdbGeneration() ? DebugInformationFormat.Pdb : DebugInformationFormat.PortablePdb; } else { // Based on https://github.com/dotnet/roslyn/blob/1d28ff9ba248b332de3c84d23194a1d7bde07e4d/src/Compilers/CSharp/Portable/CommandLine/CSharpCommandLineParser.cs#L624-L640 switch (dependencyContextOptions.DebugType.ToLower()) { case "none": // There isn't a way to represent none in DebugInformationFormat. // We'll set EmitPdb to false and let callers handle it by setting a null pdb-stream. _emitPdb = false; return new EmitOptions(); case "portable": debugInformationFormat = DebugInformationFormat.PortablePdb; break; case "embedded": // Roslyn does not expose enough public APIs to produce a binary with embedded pdbs. // We'll produce PortablePdb instead to continue providing a reasonable user experience. debugInformationFormat = DebugInformationFormat.PortablePdb; break; case "full": case "pdbonly": debugInformationFormat = SymbolsUtility.SupportsFullPdbGeneration() ? DebugInformationFormat.Pdb : DebugInformationFormat.PortablePdb; break; default: throw new InvalidOperationException(Resources.FormatUnsupportedDebugInformationFormat(dependencyContextOptions.DebugType)); } } var emitOptions = new EmitOptions(debugInformationFormat: debugInformationFormat); return emitOptions; } private static CSharpCompilationOptions GetCompilationOptions( IHostingEnvironment hostingEnvironment, DependencyContextCompilationOptions dependencyContextOptions) { var csharpCompilationOptions = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary); // Disable 1702 until roslyn turns this off by default csharpCompilationOptions = csharpCompilationOptions.WithSpecificDiagnosticOptions( new Dictionary<string, ReportDiagnostic> { {"CS1701", ReportDiagnostic.Suppress}, // Binding redirects {"CS1702", ReportDiagnostic.Suppress}, {"CS1705", ReportDiagnostic.Suppress} }); if (dependencyContextOptions.AllowUnsafe.HasValue) { csharpCompilationOptions = csharpCompilationOptions.WithAllowUnsafe( dependencyContextOptions.AllowUnsafe.Value); } OptimizationLevel optimizationLevel; if (dependencyContextOptions.Optimize.HasValue) { optimizationLevel = dependencyContextOptions.Optimize.Value ? OptimizationLevel.Release : OptimizationLevel.Debug; } else { optimizationLevel = hostingEnvironment.IsDevelopment() ? OptimizationLevel.Debug : OptimizationLevel.Release; } csharpCompilationOptions = csharpCompilationOptions.WithOptimizationLevel(optimizationLevel); if (dependencyContextOptions.WarningsAsErrors.HasValue) { var reportDiagnostic = dependencyContextOptions.WarningsAsErrors.Value ? ReportDiagnostic.Error : ReportDiagnostic.Default; csharpCompilationOptions = csharpCompilationOptions.WithGeneralDiagnosticOption(reportDiagnostic); } return csharpCompilationOptions; } private static CSharpParseOptions GetParseOptions( IHostingEnvironment hostingEnvironment, DependencyContextCompilationOptions dependencyContextOptions) { var configurationSymbol = hostingEnvironment.IsDevelopment() ? "DEBUG" : "RELEASE"; var defines = dependencyContextOptions.Defines.Concat(new[] { configurationSymbol }); var parseOptions = new CSharpParseOptions(preprocessorSymbols: defines); if (!string.IsNullOrEmpty(dependencyContextOptions.LanguageVersion)) { if (LanguageVersionFacts.TryParse(dependencyContextOptions.LanguageVersion, out var languageVersion)) { parseOptions = parseOptions.WithLanguageVersion(languageVersion); } else { Debug.Fail($"LanguageVersion {languageVersion} specified in the deps file could not be parsed."); } } return parseOptions; } } }
41.101695
185
0.618144
[ "Apache-2.0" ]
Kartikexp/MvcDotnet
src/Microsoft.AspNetCore.Mvc.Razor/Internal/CSharpCompiler.cs
9,702
C#