Beispiel #1
0
        public override void CheckSemantics(Scope scope, Report report)
        {
            Create();

            #region Eliminar las definiciones ya existentes
            List <string> types_names = new List <string>();

            for (int i = 0; i < simpleTypes.Count; i++)
            {
                if (simpleTypes[i].id.name == "string" || simpleTypes[i].id.name == "int" || scope.ShortFindType(simpleTypes[i].id.name) != null || types_names.Contains(simpleTypes[i].id.name))
                {
                    report.Add(simpleTypes[i].Line, simpleTypes[i].CharPositionInLine, string.Format("Cant define type {0}", simpleTypes[i].id.name));
                    returnType = scope.FindType("error");
                    return;
                }

                types_names.Add(simpleTypes[i].id.name);
            }

            #endregion

            Graph graph       = new Graph(simpleTypes);
            var   toAnalize   = graph.pending;
            var   circularity = graph.circularity;

            foreach (var item in circularity)
            {
                report.Add(item[0].Line, item[0].CharPositionInLine, string.Format("Type {0} is circular", item[0].id.name));
                returnType = scope.FindType("error");
                return;
            }
            foreach (var item in toAnalize)
            {
                scope.AddType(item.id.name, Types.User, item);
            }

            foreach (var item in toAnalize)
            {
                item.CheckSemantics(scope, report);
                if (item.returnType != null && item.returnType.isError)
                {
                    returnType = scope.FindType("error");
                    return;
                }

                item.returnType = scope.FindType("void");
            }

            for (int i = 0; i < toAnalize.Count; i++)
            {
                scope.AddType(toAnalize[i].id.name, Types.User, toAnalize[i]);
                if (!toAnalize[i].returnType.isError)
                {
                    toAnalize[i].SetDeclaredType(scope);
                }
            }
        }
Beispiel #2
0
 public void InitScope(Scope scope)
 {
     //predifined types
     scope.AddType("int", TigerType.GetType <IntType>());
     scope.AddType("string", TigerType.GetType <StringType>());
     //We add ErrorType to scope, because when a variable is not defined
     //we say that it has ErrorType, so ErrorType must be in the
     //Scope.
     scope.AddType(TigerType.GetType <ErrorType>().TypeID, TigerType.GetType <StringType>());
 }
Beispiel #3
0
        private static SyntaxNode Repository(SyntaxNode node, Scope scope)
        {
            //Hubo problemas con el templatecito bonito,
            //Roslyn espera que tu reemplaces una clase con otra
            //Por tanto hay que escupir la clase nada mas y annadir
            //la interfaz al scope

            var repository = node as ClassDeclarationSyntax;

            if (repository == null)
                throw new InvalidOperationException();

            //Vamos a suponer que quieres cambiar los metodos para que sean UnitOfWork
            //solo un ejemplo.
            var typeName = repository.Identifier.ToString();
            var className = typeName + "Repository";
            var interfaceName = "I" + typeName + "Repository";

            var methods = repository
                .DescendantNodes()
                .OfType<MethodDeclarationSyntax>();

            var @interface = repoInterface.Get<InterfaceDeclarationSyntax>(interfaceName)
                .AddMembers(methods
                    .Select(method => CSharp.MethodDeclaration(method.ReturnType, method.Identifier)
                        .WithParameterList(method.ParameterList)
                        .WithSemicolonToken(Roslyn.semicolon))
                    .ToArray());

            scope.AddType(@interface);

            return repoClass.Get<ClassDeclarationSyntax>(className, typeName, interfaceName)
                .AddMembers(methods.ToArray());
        }
Beispiel #4
0
        private static void createRemoteType(ClassDeclarationSyntax @class, Scope scope, out MethodDeclarationSyntax creation)
        {
            var originalName = @class.Identifier.ToString();
            var typeName     = "__remote" + originalName;

            creation = Templates
                       .RemoteMethod
                       .Get <MethodDeclarationSyntax>(typeName, originalName);

            scope.AddType(@class
                          .WithIdentifier(CSharp.ParseToken(typeName))
                          .WithBaseList(CSharp.BaseList(CSharp.SeparatedList(new BaseTypeSyntax[] {
                CSharp.SimpleBaseType(CSharp.ParseTypeName(originalName))
            })))
                          .WithAttributeLists(CSharp.List <AttributeListSyntax>())
                          .WithMembers(CSharp.List(
                                           createRemoteMethods(@class)
                                           .Union(createRemoteConstructors(@class, typeName))
                                           .Union(new MemberDeclarationSyntax[] {
                Templates.RemoteId,
                Templates.RemoteDispatch,
                Templates.RemoteSerialize,
                Templates.RemoteDeserialize
            }))));
        }
Beispiel #5
0
        public void TestPopulate_InvalidUsage(Type to)
        {
            Scope scope = new Scope();

            scope.AddType(to);

            Throws <InvalidOperationException>(() => new UnityContainerPopulator(scope.GetAppDomain()).Populate());
        }
 public override void AddToScope(Scope scope)
 {
     if (scope.ContainsType(Name))
     {
         scope.Log.Error(string.Format("Type '{0}' already defined", Name), Line, Column);
     }
     else
     {
         scope.AddType(this);
     }
 }
Beispiel #7
0
        public void TestPopulate_WithName()
        {
            Scope scope = new Scope();

            scope.AddType(typeof(ClassWithName));

            IUnityContainer container = new UnityContainerPopulator(scope.GetAppDomain()).Populate();

            ClassWithName result = container.Resolve <ClassWithName>("my-type");

            IsNotNull(result);
        }
Beispiel #8
0
        public override bool VisitAlias(TypeAliasAST alias)
        {
            //se asume que no habra problema
            alias.ReturnType = TigerType.GetType <NoType>();
            //la clase base verifica q el id del type sea valido
            //aqui si se ve q el return true hace falta
            if (VisitTypeDeclaration(alias))
            {
                TigerType tt;
                //se verifica que exista el tipo del cual se esta creando un alias
                if (_scope.HasType(alias.AliasToWho, out tt) != ScopeLocation.NotDeclared)
                {
                    //se anade una nueva entrada del mismo type, lo q con otro id
                    _scope.AddAlias(alias.TypeId, alias.AliasToWho);
                    return(true);
                }
                int savedErrorPos = _errorListener.Count;
                //manejador de evento
                _scope.TypeAdded += (sender, args) =>
                {
                    if (args.TypeName == alias.AliasToWho)
                    {
                        _scope.AddType(alias.TypeId, args.NewType);
                    }
                };

                //manejador de evento
                _scope.FinalizeScope += (sender, args) =>
                {
                    if (sender.HasType(alias.AliasToWho) == ScopeLocation.NotDeclared)
                    {
                        _errorListener.Insert(savedErrorPos, AnalysisError.TypeIsNotDefined(alias, alias.AliasToWho));
                        alias.ReturnType = TigerType.GetType <ErrorType>();
                    }
                };
                return(true);
            }
            return(false);
        }
Beispiel #9
0
        public void TestPopulate_WithName()
        {
            Scope scope = new Scope();

            scope.AddType(typeof(ProviderWithNamedFactories));

            IUnityContainer container = new UnityContainerPopulator(scope.GetAppDomain()).Populate();

            string val1 = container.Resolve <string>("factory1");
            string val2 = container.Resolve <string>("factory2");

            AreEqual("Foo", val1);
            AreEqual("Bar", val2);
        }
Beispiel #10
0
        public void TestPopulate(Type providerType, Type expectedFrom, Type expectedTo, Type expectedInstanceLifetimeManagerType)
        {
            Scope scope = new Scope();

            scope.AddType(providerType);

            IUnityContainer container = new UnityContainerPopulator(scope.GetAppDomain()).Populate();

            IList <IContainerRegistration> result = container.Registrations.ToArray();

            AreEqual(2, result.Count);
            IsUnityContainerRegistration(result[0]);
            IsExpectedRegisteredContainer(result[1], expectedFrom, expectedTo, expectedInstanceLifetimeManagerType);
        }
Beispiel #11
0
        private static SyntaxNode Repository(SyntaxNode node, Scope scope)
        {
            //Hubo problemas con el templatecito bonito,
            //Roslyn espera que tu reemplaces una clase con otra
            //Por tanto hay que escupir la clase nada mas y annadir
            //la interfaz al scope

            var repository = node as ClassDeclarationSyntax;

            if (repository == null)
            {
                throw new InvalidOperationException();
            }

            //Vamos a suponer que quieres cambiar los metodos para que sean UnitOfWork
            //solo un ejemplo.
            var typeName      = repository.Identifier.ToString();
            var className     = typeName + "Repository";
            var interfaceName = "I" + typeName + "Repository";

            var methods = repository
                          .DescendantNodes()
                          .OfType <MethodDeclarationSyntax>();

            var @interface = repoInterface.Get <InterfaceDeclarationSyntax>(interfaceName)
                             .AddMembers(methods
                                         .Select(method => CSharp.MethodDeclaration(method.ReturnType, method.Identifier)
                                                 .WithParameterList(method.ParameterList)
                                                 .WithSemicolonToken(Roslyn.semicolon))
                                         .ToArray());

            scope.AddType(@interface);

            return(repoClass.Get <ClassDeclarationSyntax>(className, typeName, interfaceName)
                   .AddMembers(methods.ToArray()));
        }
Beispiel #12
0
        public override void FirstSemanticCheck(List <SemanticError> errors, Scope scope)
        {
            if (!SemanticCheckAlgoritms.TopologicalSort(ClassNodes, errors))
            {
                return;
            }
            foreach (var _class in ClassNodes)
            {
                scope.AddType(_class.TypeClass.Text, new SemanticCheck.Type(_class.TypeClass.Text, scope.GetType(_class.TypeClassInherit.Text), _class));
            }
            int indexMain = -1;

            for (int i = 0; i < ClassNodes.Count; ++i)
            {
                if (ClassNodes[i].TypeClass.Text == "Main")
                {
                    indexMain = i;
                }
            }
            if (indexMain == -1)
            {
                errors.Add(new SemanticError(Line, Column, TypeError.NotClassMainDefine));
                return;
            }

            bool mainFunction = false;

            foreach (var item in ClassNodes[indexMain].Features)
            {
                if (item is Feature.MethodNode)
                {
                    var method = item as Feature.MethodNode;
                    if (method.Id.Text == "main" && method.Arguments.Count == 0)
                    {
                        mainFunction = true;
                    }
                }
            }

            if (!mainFunction)
            {
                errors.Add(new SemanticError(ClassNodes[indexMain].Line, ClassNodes[indexMain].Column, TypeError.NotMethodMainInClassMain));
                return;
            }

            foreach (var cclass in ClassNodes)
            {
                if (!scope.IsDefinedType(cclass.TypeClassInherit.Text, out SemanticCheck.Type type))
                {
                    errors.Add(new SemanticError(cclass.Line, cclass.Column, TypeError.RepeatClass));
                    return;
                }
                if (new List <string> {
                    "Bool", "Int", "String"
                }.Contains(type.Text))
                {
                    errors.Add(new SemanticError(cclass.Line, cclass.Column, TypeError.RepeatClass));
                    return;
                }
                cclass.FirstSemanticCheck(errors, scope);
            }
        }
Beispiel #13
0
        private static SyntaxNode LinkServerInstance(ServerInstance app, Func <ServerModel, Scope, SyntaxNode> transform, Scope scope)
        {
            //a list of statements and types to be added
            var statements = new List <StatementSyntax>();

            foreach (var node in app.Nodes)
            {
                var appStatement = default(StatementSyntax);
                scope.AddType(LinkNode(node, out appStatement));

                if (appStatement != null)
                {
                    statements.Add(appStatement);
                }
            }

            //create the http start
            //
            var except = Templates
                         .StringArray
                         .Get <ArrayCreationExpressionSyntax>()
                         .WithInitializer(StringArrayInitializer(app
                                                                 .Nodes
                                                                 .SelectMany(node => node.HostedClasses)));

            //find functional filters
            var filters = new List <ExpressionSyntax>();

            if (app.SQL != null)
            {
                var connectionString = default(ExpressionSyntax);
                if (app.SQL.ConnectionString != null)
                {
                    Debug.Assert(app.SQL.ConnectionId == null);
                    connectionString = Roslyn.Quoted(app.SQL.ConnectionString);
                }
                else
                {
                    Debug.Assert(app.SQL.ConnectionId != null);
                    connectionString = Templates
                                       .SqlConnectionStringFromConfig
                                       .Get <ExpressionSyntax>(
                        Roslyn.Quoted(app.SQL.ConnectionId));
                }

                var connectionClass = app.SQL.ConnectionInstantiator ?? "SqlConnection";
                filters.Add(Templates
                            .SqlFilter
                            .Get <ExpressionSyntax>(
                                connectionString,
                                CSharp.IdentifierName(connectionClass)));
            }

            filters.Add(Templates.UserFilter);

            //start the server
            statements.Add(Templates
                           .StartHttpServer
                           .Get <StatementSyntax>(
                               Roslyn.Quoted(app.Host.Address),
                               Roslyn.Quoted(app.Identity),
                               Roslyn.Quoted(app.StaticFiles, escaped: true),
                               Roslyn.Constant(app.Threads),
                               except,
                               Roslyn.Constant(app.Nodes.Count),
                               app.Id,
                               Templates
                               .EmptyArray
                               .WithInitializer(CSharp.InitializerExpression(
                                                    SyntaxKind.ArrayInitializerExpression, CSharp.SeparatedList(
                                                        filters)))));

            //generate configuration class
            var result = Templates
                         .ServerInstance
                         .Get <ClassDeclarationSyntax>(app.Id, Roslyn.Quoted(app.Id));

            var runMethods = result
                             .DescendantNodes()
                             .OfType <MethodDeclarationSyntax>()
                             .Where(method => method.Identifier.ToString() == "Run");

            return(result.ReplaceNodes(runMethods,
                                       (on, nn) => nn.AddBodyStatements(statements.ToArray())));
        }
Beispiel #14
0
        private static SyntaxNode Compile(SyntaxNode node, Scope scope, bool isSingleton, Options options)
        {
            Debug.Assert(node is ClassDeclarationSyntax);
            var @class = (node as ClassDeclarationSyntax)
                         .AddBaseListTypes(
                CSharp.SimpleBaseType(CSharp.ParseTypeName(
                                          "ConcurrentObject")));

            if (options.GenerateInterface)
            {
                @class = @class.AddBaseListTypes(
                    CSharp.SimpleBaseType(CSharp.ParseTypeName(
                                              "I" + (node as ClassDeclarationSyntax).Identifier.ToString())));
            }

            var className = @class.Identifier.ToString();

            var ctx = new Class(className, scope, isSingleton);

            scope.set <Class>(ctx);

            foreach (var member in @class.Members)
            {
                if (member is PropertyDeclarationSyntax)
                {
                    compileProperty(member as PropertyDeclarationSyntax, ctx, scope);
                }
                else if (member is MethodDeclarationSyntax)
                {
                    var method = member as MethodDeclarationSyntax;
                    if (compileMethod(method, ctx, scope, options, isSingleton))
                    {
                        var isVoid   = method.ReturnType.ToString() == "void";
                        var taskArgs = isVoid
                            ? new[]
                        {
                            CSharp.Argument(Templates.NullCancelationToken),
                            CSharp.Argument(Roslyn.@null),
                            CSharp.Argument(Roslyn.@null)
                        }
                            : new[]
                        {
                            CSharp.Argument(Templates.NullCancelationToken)
                        };

                        var taskCall = CSharp
                                       .InvocationExpression(
                            CSharp.IdentifierName(method.Identifier),
                            CSharp.ArgumentList(CSharp.SeparatedList(
                                                    method
                                                    .ParameterList
                                                    .Parameters
                                                    .Select(parameter => CSharp
                                                            .Argument(CSharp.IdentifierName(parameter.Identifier)))
                                                    .Union(
                                                        taskArgs))));

                        var newMethod = method
                                        .AddAttributeLists(CSharp.AttributeList(CSharp.SeparatedList(new[] { CSharp
                                                                                                             .Attribute(CSharp
                                                                                                                        .ParseName("Concurrent")) })))
                                        .WithBody(CSharp.Block()
                                                  .WithStatements(CSharp.List(new[] {
                            isVoid
                                        ? Templates
                            .SynchVoidMethod
                            .Get <StatementSyntax>(taskCall)
                                        : Templates
                            .SynchReturnMethod
                            .Get <StatementSyntax>(taskCall)
                        })));

                        if (isSingleton && ctx.willReplace(method))
                        {
                            //singleton methods must change into __methodName
                            var fs = (newMethod
                                      .Body
                                      .Statements
                                      .First() as ExpressionStatementSyntax)
                                     .Expression as InvocationExpressionSyntax;

                            var newId = "__" + method.Identifier.ToString();
                            newMethod = newMethod
                                        .ReplaceNode(fs, fs.WithExpression(CSharp.IdentifierName(newId)))
                                        .WithIdentifier(CSharp.ParseToken(newId));
                        }

                        ctx.Replace(method, newMethod);
                    }
                }
            }

            //all concurrent compilation has been done, produce
            @class = ctx.Update(@class);

            if (isSingleton)
            {
                @class = @class.AddMembers(
                    Templates.SingletonField
                    .Get <MemberDeclarationSyntax>(@class.Identifier),
                    Templates.SingletonInit
                    .Get <MemberDeclarationSyntax>(@class.Identifier));
            }

            //generate the interface
            if (options.GenerateInterface)
            {
                scope.AddType(CreateInterface(@class));
            }

            if (options.GenerateRemote)
            {
                //add a remote type, to be used with an identity server
                var remoteMethod = null as MethodDeclarationSyntax;
                createRemoteType(@class, scope, out remoteMethod);
                @class = @class.AddMembers(remoteMethod);
            }

            if (options.GenerateID)
            {
                @class = @class.AddMembers(Templates
                                           .ObjectId
                                           .Get <MemberDeclarationSyntax>());
            }

            //schedule linking
            var document = scope.GetDocument();

            return(document.change(@class, Link(ctx), null));
        }