public IEnumerable <StatementSyntax> GetInitialization() { var inputEnumeratorType = _ienumerator.CreateGenericSyntax(_inputType); yield return(SH.LocalDeclaration(inputEnumeratorType, enumerator, SF.IdentifierName(inputParameter).Dot("GetEnumerator").Invoke())); }
private static MethodDeclarationSyntax GenerateCreateSut( ClassDeclarationSyntax classDeclaration, MethodInspector constructorInspector) { var methodBuilder = new MethodBuilder(GH.IdentifierToken("CreateSut")) .Modifiers(Modifiers.Private); var constructorParameters = constructorInspector .Parameters .Select(p => SF.Argument( EGH.MemberAccess( EGH.ThisMemberAccess( GH.Identifier(MockName(p.Name)) ), GH.Identifier("Object") ) ) ); methodBuilder.ArrowBody( EGH.Arrow( EGH.CreateObject( SF.IdentifierName(classDeclaration.Identifier), constructorParameters.ToArray()))); return(methodBuilder.Build()); }
public IEnumerable <StatementSyntax> GetFinalization() { yield return(SF.IfStatement(SF.BinaryExpression(SyntaxKind.GreaterThanExpression, SF.IdentifierName(outputIndex), SH.Literal(0)), SF.ExpressionStatement(SF.IdentifierName(outputParameter).Dot("Write").Invoke(SF.IdentifierName(outputBuffer), SH.Literal(0), SF.IdentifierName(outputIndex))))); yield return(SF.ReturnStatement()); }
public IEnumerable <StatementSyntax> GetYields(IEnumerable <ExpressionSyntax> yields, int numYields) { if (numYields == 0) { yield break; } if (numYields > BufferSize) { throw new NotImplementedException(); } yield return(SF.IfStatement(SF.BinaryExpression(SyntaxKind.GreaterThanExpression, SF.IdentifierName(outputIndex), SH.Literal(BufferSize - numYields)), SF.Block( SF.ExpressionStatement(SF.IdentifierName(outputParameter).Dot("Write").Invoke(SF.IdentifierName(outputBuffer), SH.Literal(0), SF.IdentifierName(outputIndex))), SH.Assignment(SF.IdentifierName(outputIndex), SH.Literal(0))))); int index = 0; foreach (var yieldSyntax in yields) { yield return(SH.Assignment(SF.ElementAccessExpression(SF.IdentifierName(outputBuffer), SF.BracketedArgumentList(SF.SingletonSeparatedList(SF.Argument( SF.BinaryExpression(SyntaxKind.AddExpression, SF.IdentifierName(outputIndex), SH.Literal(index)))))), yieldSyntax)); ++index; } yield return(SH.Assignment(SF.IdentifierName(outputIndex), SH.Literal(numYields), SyntaxKind.AddAssignmentExpression)); }
public ExpressionSyntax GetInput() { return(SF.BinaryExpression(SyntaxKind.EqualsExpression, SF.BinaryExpression(SyntaxKind.BitwiseAndExpression, SF.IdentifierName(cachedInput), SH.Literal(1)).Parenthesize(), SH.Literal(1))); }
public IEnumerable <StatementSyntax> GetMoveNext(StatementSyntax finalizer) { yield return(SF.IfStatement(SF.BinaryExpression(SyntaxKind.GreaterThanOrEqualExpression, SF.PrefixUnaryExpression(SyntaxKind.PreIncrementExpression, SF.IdentifierName(inputIndex)), SF.IdentifierName(read)), SF.Block( SH.Assignment(SF.IdentifierName(read), SF.IdentifierName(inputParameter).Dot("Read").Invoke(SF.IdentifierName(inputBuffer), SH.Literal(0), SF.IdentifierName(inputBuffer).Dot("Length"))), SF.IfStatement(SF.BinaryExpression(SyntaxKind.EqualsExpression, SF.IdentifierName(read), SH.Literal(0)), finalizer), SH.Assignment(SF.IdentifierName(inputIndex), SH.Literal(0)) ))); }
public IEnumerable <StatementSyntax> GetInitialization() { var bufferType = SF.ArrayType(SH.PredefinedType(SyntaxKind.ByteKeyword), SF.SingletonList(SF.ArrayRankSpecifier(SF.SingletonSeparatedList((ExpressionSyntax)SH.Literal(BufferSize))))); yield return(SH.LocalDeclaration(SF.IdentifierName("var"), outputBuffer, SF.ArrayCreationExpression(bufferType))); yield return(SH.LocalDeclaration(SH.PredefinedType(SyntaxKind.IntKeyword), outputIndex, SH.Literal(0))); }
public IEnumerable <StatementSyntax> GetMoveNext(StatementSyntax finalizer) { yield return(SF.IfStatement(SF.BinaryExpression(SyntaxKind.GreaterThanExpression, SF.PrefixUnaryExpression(SyntaxKind.PreIncrementExpression, SF.IdentifierName(bitIndex)), SH.Literal(7)), SF.Block(_wrapped.GetMoveNext(finalizer).Concat(new StatementSyntax[] { SH.Assignment(SF.IdentifierName(cachedInput), _wrapped.GetInput()), SH.Assignment(SF.IdentifierName(bitIndex), SH.Literal(0)) })), SF.ElseClause(SH.Assignment(SF.IdentifierName(cachedInput), SH.Literal(1), SyntaxKind.RightShiftAssignmentExpression)))); }
private static EventFieldDeclarationSyntax ToEventDclr(IEventSymbol eventSymbol) { string eventName = eventSymbol.Name; string eventType = GetEventType(eventSymbol); EventFieldDeclarationSyntax eventDclr = SF.EventFieldDeclaration( SF.VariableDeclaration(SF.IdentifierName(eventType), SF.SeparatedList(new[] { SF.VariableDeclarator(eventName) }))) .AddModifiers(SF.Token(SyntaxKind.PublicKeyword)); return(eventDclr); }
private static ClassDeclarationSyntax GenerateWriteGrain(ClassDeclarationSyntax grainClass, ITypeSymbol swmrInterface, int readReplicaCount) { string grainName = grainClass.Identifier.Text; string writerGrainName = SwmrUtils.GetWriteInterfaceName(grainName); string writerInterfaceName = SwmrUtils.GetWriteInterfaceName(swmrInterface.Name); ClassDeclarationSyntax writerGrain = GenerateClassSqueleton(writerGrainName).WithBaseList(RoslynUtils.BaseList(new[] { "Grain", writerInterfaceName })); writerGrain = RoslynUtils.AddField(writerGrain, "ITopology<string>", "_topology"); writerGrain = writerGrain.AddMembers(GenerateOnActivateAsyncMethod(readReplicaCount)); string readReplicaInterfaceName = SwmrUtils.GetReadReplicaInterfaceName(swmrInterface.Name); foreach (ISymbol member in swmrInterface.GetMembers()) { IMethodSymbol methodSymbol = member as IMethodSymbol; if (methodSymbol == null || IsReadOnlyMethod(methodSymbol) || new MethodInspector(methodSymbol).MethodName == "GetState") { continue; } MethodInspector methodInspector = new MethodInspector(methodSymbol); MethodDeclarationSyntax methodImpl = GenerateMethodDeclaration(methodInspector); methodImpl = SwmrUtils.AddSessionIdParameter(methodImpl).AddModifiers(SF.Token(SyntaxKind.PublicKeyword), SF.Token(SyntaxKind.AsyncKeyword)).WithSemicolonToken(SF.Token(SyntaxKind.None)); BlockSyntax statmentBlock = SF.Block(); statmentBlock = AddStatement(statmentBlock, "string grainId = this.GetPrimaryKeyString();"); statmentBlock = AddStatement(statmentBlock, string.Format("{0} grain = GrainFactory.GetGrain<{0}>(grainId);", swmrInterface.Name)); statmentBlock = AddStatement(statmentBlock, String.Format("{0} await grain.{1}({2});", methodInspector.ReturnType != "Task"? "var result =" : "", methodInspector.MethodName, string.Join(", ", methodInspector.MethodParams.Keys))); statmentBlock = AddStatement(statmentBlock, "GrainState state = await grain.GetState();"); statmentBlock = AddStatement(statmentBlock, "string sessionNode = _topology.GetNode(sessionId);"); statmentBlock = AddStatement(statmentBlock, "IEnumerable<string> otherNodes = _topology.Nodes.Where(node => node != sessionNode);"); ForEachStatementSyntax forEachStatement = SF.ForEachStatement( SF.PredefinedType(SF.Token(SyntaxKind.StringKeyword)), SF.Identifier("node"), SF.IdentifierName("otherNodes"), SF.Block(SF.ParseStatement(GenerateSetStateStmt(readReplicaInterfaceName, @"node"))) ); statmentBlock = statmentBlock.AddStatements(forEachStatement); statmentBlock = AddStatement(statmentBlock, (string.Format("{0} {1}", "await", GenerateSetStateStmt(readReplicaInterfaceName, @"sessionNode")))); if (methodInspector.ReturnType != "Task") { statmentBlock = AddStatement(statmentBlock, "return result;"); } methodImpl = methodImpl.WithBody(statmentBlock); writerGrain = writerGrain.AddMembers(methodImpl); } return(writerGrain); }
public static TypeSyntax CreateSyntax(this INamedTypeSymbol symbol) { Contract.Requires(symbol.CanBeReferencedByName); if (symbol.IsGenericType) { return(symbol.CreateGenericSyntax(symbol.TypeArguments.Select(s => (TypeSyntax)(((INamedTypeSymbol)s).CreateSyntax())).ToArray())); } else { return(SF.IdentifierName(SF.Identifier(symbol.Name))); } }
public IEnumerable <StatementSyntax> GetInitialization() { yield return(SH.LocalDeclaration(SF.IdentifierName("var"), output, SF.ObjectCreationExpression(_stringBuilder.CreateSyntax()) .WithArgumentList(SF.ArgumentList(SF.SeparatedList <ArgumentSyntax>())))); var bufferType = SF.ArrayType(SH.PredefinedType(SyntaxKind.CharKeyword), SF.SingletonList(SF.ArrayRankSpecifier(SF.SingletonSeparatedList((ExpressionSyntax)SH.Literal(BufferSize))))); yield return(SH.LocalDeclaration(SF.IdentifierName("var"), outputBuffer, SF.ArrayCreationExpression(bufferType))); yield return(SH.LocalDeclaration(SH.PredefinedType(SyntaxKind.IntKeyword), outputIndex, SH.Literal(0))); }
private BasePropertyDeclarationSyntax CreatePropertyDclr(IMethodSymbol methodSymbol, string propType) { if (methodSymbol.IsIndexerAccessor()) { IndexerDeclarationSyntax indexerDclr = SF.IndexerDeclaration( SF.ParseTypeName(propType)) .WithExplicitInterfaceSpecifier(SF.ExplicitInterfaceSpecifier( SF.IdentifierName(methodSymbol.GetContainingInterfaceGenericQualifiedName()))); indexerDclr = indexerDclr.AddParameterListParameters( RoslynUtils.GetMethodParameterSyntaxList(methodSymbol).ToArray()); return(indexerDclr); } string propName = methodSymbol.AssociatedSymbol.Name; PropertyDeclarationSyntax propDclr = SF.PropertyDeclaration(SF.ParseTypeName(propType), SF.Identifier(propName)) .WithExplicitInterfaceSpecifier(SF.ExplicitInterfaceSpecifier( SF.IdentifierName(methodSymbol.GetContainingInterfaceGenericQualifiedName()))); return(propDclr); }
public SyntaxTree Generate(TransducerCompilation source) { var stb = source.Transducer; var sourceNamespace = source.DeclarationType.ContainingNamespace.DeclaringSyntaxReferences[0].GetSyntax() as NamespaceDeclarationSyntax; if (sourceNamespace == null) { throw new CodeGenerationException("Containing namespace declaration not found for " + source.DeclarationType); } // Follow the declaration of the original (partial) class var classDecl = source.DeclarationType.DeclaringSyntaxReferences.Select(r => r.GetSyntax()).OfType <ClassDeclarationSyntax>().FirstOrDefault() .WithLeadingTrivia().WithTrailingTrivia() // Strip any trivia .WithMembers(SF.List <MemberDeclarationSyntax>()) .WithAttributeLists(SF.List <AttributeListSyntax>()); if (classDecl == null) { throw new Exception("Class declaration for " + source.DeclarationType + " not found"); } classDecl = _concreteCG.Generate(source, stb, classDecl); var automataNamespace = SF.IdentifierName("Microsoft").Qualified(SF.IdentifierName("Automata")).Qualified(SF.IdentifierName("CSharpFrontend")); var root = SF.CompilationUnit() .WithUsings(SF.List(new[] { SF.UsingDirective(SF.IdentifierName("System")), SF.UsingDirective(SF.IdentifierName("System").Qualified(SF.IdentifierName("Text"))), SF.UsingDirective(SF.IdentifierName("System").Qualified(SF.IdentifierName("IO"))), SF.UsingDirective(SF.IdentifierName("System").Qualified(SF.IdentifierName("Collections")).Qualified(SF.IdentifierName("Generic"))), SF.UsingDirective(automataNamespace), })) .WithMembers(SF.SingletonList((MemberDeclarationSyntax)SF.NamespaceDeclaration(sourceNamespace.Name) .WithMembers(SF.SingletonList((MemberDeclarationSyntax)classDecl)))); var normalized = root.NormalizeWhitespace(); return(SF.SyntaxTree(normalized)); }
static IEnumerable <MemberDeclarationSyntax> ColumnToMembers(string column, IEnumerable <IFieldSymbol> fields) { var fieldsList = fields.ToList(); TypeSyntax columnElementType; if (fieldsList.Count > 1) { var fieldGroupTypeName = SF.IdentifierName($"{column}_t"); yield return(SF.StructDeclaration(fieldGroupTypeName.Identifier) .WithMembers(SF.List(fields.Select(x => SF.FieldDeclaration(SF.VariableDeclaration( SF.IdentifierName(x.Type.Name), SF.SingletonSeparatedList(SF.VariableDeclarator(x.Name))))).Cast <MemberDeclarationSyntax>()))); columnElementType = fieldGroupTypeName; } else { columnElementType = SF.IdentifierName(fields.First().Type.Name); } yield return(SF.FieldDeclaration(SF.VariableDeclaration( SF.ArrayType(columnElementType, SF.SingletonList(SF.ArrayRankSpecifier())), SF.SingletonSeparatedList(SF.VariableDeclarator(column))))); }
public IEnumerable <StatementSyntax> GetMoveNext(StatementSyntax finalizer) { yield return(SF.IfStatement(SF.PrefixUnaryExpression(SyntaxKind.LogicalNotExpression, SF.IdentifierName(enumerator).Dot("MoveNext").Invoke()), finalizer)); }
public static AttributeSyntax AttributeWithArgument(string attributeName, params string[] attributeArguments) { return(SF.Attribute(SF.IdentifierName(attributeName), SF.AttributeArgumentList() .WithArguments(SF.SeparatedList(attributeArguments.Select(arg => SF.AttributeArgument(SF.IdentifierName(arg))))))); }
public static AttributeSyntax Attribute(string attributeName) { return(SF.Attribute(SF.IdentifierName(attributeName))); }
private static async Task <Document> GenerateCodeFixAsync(Document document, ClassDeclarationSyntax node, CancellationToken cancellationToken) { var semanticModel = await document.GetSemanticModelAsync(cancellationToken); var symbol = semanticModel.GetDeclaredSymbol(node); if (symbol is null) { throw new NullReferenceException(nameof(symbol)); } var syntaxTree = await document.GetSyntaxTreeAsync(cancellationToken); if (syntaxTree is null) { throw new NullReferenceException(nameof(syntaxTree)); } var flags = GetMetadataFlags(symbol); List <AttributeSyntax> list = new(3); if ((flags & MetadataFlags.HasEditorGroup) == 0) { var args = SF.ParseAttributeArgumentList("(group_Unknown)"); list.Add(SF.Attribute(SF.IdentifierName("EditorGroup"), args)); } if ((flags & MetadataFlags.HasMetaImage) == 0) { var args = SF.ParseAttributeArgumentList("(tex_)"); list.Add(SF.Attribute(SF.IdentifierName("MetaImage"), args)); } if ((flags & MetadataFlags.HasMetaInfo) == 0) { string className = symbol.Name; var args = SF.ParseAttributeArgumentList($"({nameof(Lang)}.Default, \"{ParsePascalName(className)}\", \"todo\")"); list.Add(SF.Attribute(SF.IdentifierName("MetaInfo"), args)); var args2 = SF.ParseAttributeArgumentList($"({nameof(Lang)}.{nameof(Lang.schinese)}, \"\", \"\")"); list.Add(SF.Attribute(SF.IdentifierName("MetaInfo"), args2)); } if ((flags & MetadataFlags.HasMetaType) == 0) { MetaType metaType = 0; // 0 = MetaType.Undefined if (symbol.HasBaseType("AncientMysteries.Items.AMStaff")) { metaType = MetaType.Magic; goto mustBeIt; } if (symbol.HasBaseType("AncientMysteries.Items.AMMelee")) { metaType = MetaType.Melee; goto mustBeIt; } if (symbol.HasBaseType("AncientMysteries.Items.AMChestPlate", "AncientMysteries.Items.AMBoots", "AncientMysteries.Items.AMEquipment", "AncientMysteries.Items.AMHelmet")) { metaType = MetaType.Equipment; goto mustBeIt; } if (symbol.HasBaseType("AncientMysteries.Items.AMThrowable")) { metaType = MetaType.Throwable; goto mustBeIt; } if (symbol.HasBaseType("AncientMysteries.Items.AMDecoration")) { metaType = MetaType.Decoration; goto mustBeIt; } if (symbol.HasBaseType("AncientMysteries.Items.AMGun")) { metaType = MetaType.Gun; goto mustBeIt; } mustBeIt: var args = SF.ParseAttributeArgumentList($"(MetaType.{metaType})"); list.Add(SF.Attribute(SF.IdentifierName("MetaType"), args)); } if (list.Count == 0) { return(document); } var updatedNode = node; foreach (var item in list) { updatedNode = updatedNode.AddAttributeLists(SF.AttributeList(SF.SingletonSeparatedList(item))); } var root = await syntaxTree.GetRootAsync(cancellationToken); var updatedSyntaxTree = root.ReplaceNode(node, updatedNode); return(document.WithSyntaxRoot(updatedSyntaxTree)); }
private static async Task <Document> GenerateDiscriminatedUnion( Document document, ClassDeclarationSyntax classDeclarationSyntax, CancellationToken cancellationToken) { var rootNode = classDeclarationSyntax.Parent; if (rootNode == null) { return(document); } var duMembers = GetCandidateMethods(classDeclarationSyntax); if (duMembers.Count == 0) { return(document); } var factoryMethodRewriter = new FactoryMethodRewriter(); var newClassDeclaration = factoryMethodRewriter.Visit(classDeclarationSyntax); rootNode = rootNode.ReplaceNode(classDeclarationSyntax, newClassDeclaration); List <(MethodDeclarationSyntax method, ClassDeclarationSyntax cl)> candidates = duMembers.Select(m => (m, FindCurrentCaseDeclaration(rootNode, GetGeneratedClassName(m)))) .ToList(); var declarationsCleaner = new ClassOccurencesCleaner(candidates.Select(p => p.cl).Where(p => p != null).ToList()); rootNode = declarationsCleaner.Visit(rootNode); // TODO: Methods returning types defined in other assemblies should probably be rejected, // but lets say it is user's responsibility to use this refactoring wisely. var baseClassIdentifier = SF.IdentifierName(classDeclarationSyntax.Identifier); foreach (var(duCandidate, prevDeclaration) in candidates) { var generatedClassName = GetGeneratedClassName(duCandidate); if (generatedClassName == default) { return(document); } var properties = duCandidate.ParameterList.Parameters.Select(ToProperty).ToList(); var constructorDeclaration = properties.Count > 0 ? ConstructorGenerationHelper.FromPropertiesWithAssignments( generatedClassName, properties) : null; var members = new List <MemberDeclarationSyntax>(properties); rootNode = UpdateOrAddCaseDefinition(rootNode, generatedClassName, baseClassIdentifier, properties, constructorDeclaration, prevDeclaration); } // Update document var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); var root = await tree.GetRootAsync(cancellationToken).ConfigureAwait(false); var newRoot = root.ReplaceNode(classDeclarationSyntax.Parent, rootNode); var newDocument = document.WithSyntaxRoot(newRoot); return(newDocument); }
public static MemberAccessExpressionSyntax Dot(this ExpressionSyntax expression, string field) { return(SF.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, expression, SF.IdentifierName(field))); }
public ExpressionSyntax GetInput() { return(SF.IdentifierName(enumerator).Dot("Current")); }
public static BaseListSyntax BaseList(IEnumerable <string> names) { return(SF.BaseList(SF.SeparatedList <BaseTypeSyntax>(names.Select(name => SF.SimpleBaseType(SF.IdentifierName(name)))))); }
public static ParameterSyntax CreateParameter(string type, string name) { return(SF.Parameter(new SyntaxList <AttributeListSyntax>(), new SyntaxTokenList(), SF.IdentifierName(type), SF.Identifier(new SyntaxTriviaList().Add(SF.Space), name, new SyntaxTriviaList()), null)); }
public static BaseListSyntax AddBase(BaseListSyntax baseList, string baseName) { baseList = baseList.AddTypes(SF.SimpleBaseType(SF.IdentifierName(baseName))); return(baseList); }
public ExpressionSyntax GetInput() { return(SF.ElementAccessExpression(SF.IdentifierName(inputBuffer), SF.BracketedArgumentList(SF.SingletonSeparatedList(SF.Argument(SF.IdentifierName(inputIndex)))))); }
public static ArgumentSyntax ArgumentFromIdentifier(SyntaxToken identifier) => SF.Argument(SF.IdentifierName(identifier.WithoutTrivia()));
public async Task <CodeGenResult> CodeGen(Workspace workspace, Project project) { CompilationUnitSyntax cu = SF.CompilationUnit(); var usings = new HashSet <string>(); bool copyUsings = false; foreach (Document document in project.Documents) { SyntaxTree syntaxTree = await document.GetSyntaxTreeAsync(); _semanticModel = await document.GetSemanticModelAsync(); IEnumerable <ClassDeclarationSyntax> classes = syntaxTree.GetRoot().DescendantNodes().OfType <ClassDeclarationSyntax>(); foreach (var classNode in classes) { if (!RoslynUtils.IsPublic(classNode)) { continue; } ITypeSymbol swmrInterface = FindSwmrInterface(classNode); if (swmrInterface == null) { continue; } var namespaceNode = classNode.Parent as NamespaceDeclarationSyntax; if (namespaceNode == null) { throw new Exception("A grain must be declared inside a namespace"); } usings.UnionWith(syntaxTree.GetRoot().DescendantNodes().OfType <UsingDirectiveSyntax>().Select(usingDirective => usingDirective.Name.ToString())); int replicaCount = GetReadReplicaCount(swmrInterface); NamespaceDeclarationSyntax namespaceDclr = SF.NamespaceDeclaration(SF.IdentifierName(namespaceNode.Name.ToString())).WithUsings(namespaceNode.Usings); namespaceDclr = namespaceDclr.AddMembers( GenerateWriteGrain(classNode, swmrInterface, replicaCount), GenerateReadGrain(classNode, swmrInterface, replicaCount), GenerateReadReplicaGrain(classNode, swmrInterface) ); usings.UnionWith(namespaceNode.Usings.Select(@using => @using.Name.ToString())); cu = cu.AddMembers(namespaceDclr); // only copy the usings if at least one class was generated copyUsings = true; } } if (copyUsings) { usings.UnionWith(GetCommonUsings()); } return(new CodeGenResult(Formatter.Format(cu, workspace).ToString(), usings)); }
public static IdentifierNameSyntax Identifier(string name) => SF.IdentifierName(name);
public IEnumerable <StatementSyntax> GetMoveNext(StatementSyntax finalizer) { yield return(SF.IfStatement(SF.BinaryExpression(SyntaxKind.GreaterThanOrEqualExpression, SF.PrefixUnaryExpression(SyntaxKind.PreIncrementExpression, SF.IdentifierName(inputIndex)), SF.IdentifierName(inputParameter).Dot("Length")), finalizer)); }