Exemplo n.º 1
0
        /// <summary>
        /// Extracts the place holder ids.
        /// </summary>
        public List <string> ExtractPlaceHolderIds(string fileName)
        {
            try
            {
                var sourceText = File.ReadAllText(fileName);

                var tokenizer = new DothtmlTokenizer();
                tokenizer.Tokenize(sourceText);
                var parser = new DothtmlParser();
                var tree   = parser.Parse(tokenizer.Tokens);

                var results = new List <string>();
                foreach (var node in tree.EnumerateNodes().OfType <DothtmlElementNode>())
                {
                    if (node.FullTagName == "dot:ContentPlaceHolder" || node.FullTagName == "dot:SpaContentPlaceHolder")
                    {
                        var id = node.Attributes.FirstOrDefault(a => a.AttributeName == "ID");
                        if (id != null && id.ValueNode is DothtmlValueTextNode)
                        {
                            results.Add((id.ValueNode as DothtmlValueTextNode).Text);
                        }
                    }
                }
                return(results);
            }
            catch (Exception ex)
            {
                throw new Exception($"Cannot extract ContentPlaceHolderIds from a file '{fileName}'!", ex);
            }
        }
Exemplo n.º 2
0
 public void TokenizeAndParse()
 {
     var t = new DothtmlTokenizer();
     t.Tokenize(new StringReader(data));
     var p = new DothtmlParser();
     var node = p.Parse(t.Tokens);
 }
Exemplo n.º 3
0
        protected override IEnumerable <string> GetValidationErrors()
        {
            try
            {
                ResolvedTreeRoot root;
                try
                {
                    var tokenizer = new DothtmlTokenizer();
                    tokenizer.Tokenize(Code);
                    var parser   = new DothtmlParser();
                    var node     = parser.Parse(tokenizer.Tokens);
                    var resolver = new DefaultControlTreeResolver(DotvvmConfiguration.CreateDefault());
                    root = (ResolvedTreeRoot)resolver.ResolveTree(node, Guid.NewGuid() + ".dothtml");
                }
                catch (Exception ex)
                {
                    throw new CodeValidationException("Syntax error in the DOTHTML code.", ex);
                }
                Validator.Validate(root);

                return(Enumerable.Empty <string>());
            }
            catch (CodeValidationException ex)
            {
                return(new[] { ex.Message });
            }
        }
Exemplo n.º 4
0
        /// <summary>
        /// Extracts the place holder ids.
        /// </summary>
        public List <string> ExtractPlaceHolderIds(string fileName)
        {
            try
            {
                var tokenizer = new DothtmlTokenizer();
                tokenizer.Tokenize(new FileReader(fileName));
                var parser = new DothtmlParser();
                var tree   = parser.Parse(tokenizer.Tokens);

                var results = new List <string>();
                foreach (var node in tree.EnumerateNodes().OfType <DothtmlElementNode>())
                {
                    if (node.FullTagName == "dot:ContentPlaceHolder" || node.FullTagName == "dot:SpaContentPlaceHolder")
                    {
                        var id = node.Attributes.FirstOrDefault(a => a.AttributeName == "ID");
                        if (id != null && id.Literal.GetType() == typeof(DothtmlLiteralNode))
                        {
                            results.Add(id.Literal.Value);
                        }
                    }
                }
                return(results);
            }
            catch (Exception ex)
            {
                LogService.LogError(new Exception($"Cannot extract ContentPlaceHolderIds from a file '{fileName}'!", ex));
                return(null);
            }
        }
Exemplo n.º 5
0
        public void MutableTokens()
        {
            // for incremental updates of the tree, the Text and Position must be accessible

            var tokenizer = new DothtmlTokenizer();

            tokenizer.Tokenize("some not very interesting text <!-- Comment -->");
            var parser = new DothtmlParser();
            var tree   = parser.Parse(tokenizer.Tokens);

            var textNode = tree.EnumerateNodes().OfType <DothtmlLiteralNode>().Single();

            Assert.AreEqual("some not very interesting text ", textNode.Value);

            var text    = tokenizer.Tokens[0];
            var comment = tokenizer.Tokens[2];

            Assert.AreEqual(text.Type, DothtmlTokenType.Text);
            Assert.AreEqual(tokenizer.Tokens[1].Type, DothtmlTokenType.OpenComment);
            Assert.AreEqual(comment.Type, DothtmlTokenType.CommentBody);
            Assert.AreEqual(tokenizer.Tokens[3].Type, DothtmlTokenType.CloseComment);
            Assert.AreEqual(4, tokenizer.Tokens.Count);

            text.Text             = "some little bit more interesting text";
            text.Length           = text.Text.Length;
            comment.StartPosition = "some little bit more interesting text".Length;

            Assert.AreEqual("some little bit more interesting text", textNode.Value);
        }
Exemplo n.º 6
0
        public void TokenizeAndParse()
        {
            var t = new DothtmlTokenizer();

            t.Tokenize(data);
            var p    = new DothtmlParser();
            var node = p.Parse(t.Tokens);
        }
Exemplo n.º 7
0
        /// <summary>
        /// Compiles the view and returns a function that can be invoked repeatedly. The function builds full control tree and activates the page.
        /// </summary>
        public virtual CSharpCompilation CompileView(string sourceCode, string fileName, CSharpCompilation compilation, string namespaceName, string className)
        {
            // parse the document
            var tokenizer = new DothtmlTokenizer();

            tokenizer.Tokenize(sourceCode);
            var parser = new DothtmlParser();
            var node   = parser.Parse(tokenizer.Tokens);

            var resolvedView = (ResolvedTreeRoot)controlTreeResolver.ResolveTree(node, fileName);

            var errorCheckingVisitor = new ErrorCheckingVisitor();

            resolvedView.Accept(errorCheckingVisitor);

            foreach (var token in tokenizer.Tokens)
            {
                if (token.HasError && token.Error.IsCritical)
                {
                    throw new DotvvmCompilationException(token.Error.ErrorMessage, new[] { (token.Error as BeginWithLastTokenOfTypeTokenError <DothtmlToken, DothtmlTokenType>)?.LastToken ?? token });
                }
            }

            foreach (var n in node.EnumerateNodes())
            {
                if (n.HasNodeErrors)
                {
                    throw new DotvvmCompilationException(string.Join(", ", n.NodeErrors), n.Tokens);
                }
            }

            var styleVisitor = new StylingVisitor(configuration.Styles);

            resolvedView.Accept(styleVisitor);

            var validationVisitor = new Validation.ControlUsageValidationVisitor(configuration);

            resolvedView.Accept(validationVisitor);
            if (validationVisitor.Errors.Any())
            {
                var controlUsageError = validationVisitor.Errors.First();
                throw new DotvvmCompilationException(controlUsageError.ErrorMessage, controlUsageError.Nodes.SelectMany(n => n.Tokens));
            }

            if (configuration.Debug && configuration.ApplicationPhysicalPath != null)
            {
                var addExpressionDebugvisitor = new ExpressionDebugInfoAddingVisitor(Path.Combine(configuration.ApplicationPhysicalPath, fileName));
                addExpressionDebugvisitor.VisitView(resolvedView);
            }

            var emitter          = new DefaultViewCompilerCodeEmitter();
            var compilingVisitor = new ViewCompilingVisitor(emitter, configuration.ServiceLocator.GetService <IBindingCompiler>(), className,
                                                            b => configuration.ServiceLocator.GetService <IBindingIdGenerator>().GetId(b, fileName));

            resolvedView.Accept(compilingVisitor);

            return(AddToCompilation(compilation, emitter, fileName, namespaceName, className));
        }
Exemplo n.º 8
0
        /// <summary>
        /// Parses text from ITextBuffer and returns root node of syntax tree.
        /// </summary>
        /// <param name="buffer"></param>
        /// <returns></returns>
        public static DothtmlRootNode GetDothtmlRootNode(this ITextBuffer buffer)
        {
            DothtmlTokenizer t = new DothtmlTokenizer();

            t.Tokenize(new StringReader(buffer.CurrentSnapshot.GetText()));
            var parser = new DothtmlParser();

            return(parser.Parse(t.Tokens));
        }
Exemplo n.º 9
0
        /// <summary>
        /// Compiles the view and returns a function that can be invoked repeatedly. The function builds full control tree and activates the page.
        /// </summary>
        public virtual (ControlBuilderDescriptor, Func <CSharpCompilation>) CompileView(string sourceCode, string fileName, CSharpCompilation compilation, string namespaceName, string className)
        {
            // parse the document
            var tokenizer = new DothtmlTokenizer();

            tokenizer.Tokenize(sourceCode);
            var parser = new DothtmlParser();
            var node   = parser.Parse(tokenizer.Tokens);

            var resolvedView = (ResolvedTreeRoot)controlTreeResolver.ResolveTree(node, fileName);

            return(new ControlBuilderDescriptor(resolvedView.DataContextTypeStack.DataContextType, resolvedView.Metadata.Type), () => {
                var errorCheckingVisitor = new ErrorCheckingVisitor();
                resolvedView.Accept(errorCheckingVisitor);

                foreach (var token in tokenizer.Tokens)
                {
                    if (token.HasError && token.Error.IsCritical)
                    {
                        throw new DotvvmCompilationException(token.Error.ErrorMessage, new[] { (token.Error as BeginWithLastTokenOfTypeTokenError <DothtmlToken, DothtmlTokenType>)?.LastToken ?? token });
                    }
                }

                foreach (var n in node.EnumerateNodes())
                {
                    if (n.HasNodeErrors)
                    {
                        throw new DotvvmCompilationException(string.Join(", ", n.NodeErrors), n.Tokens);
                    }
                }

                var bindingResourceRegisteringVisitor = this.bindingResourceRegisteringVisitor();
                resolvedView.Accept(bindingResourceRegisteringVisitor);

                var styleVisitor = new StylingVisitor(configuration);
                resolvedView.Accept(styleVisitor);

                var contextSpaceVisitor = new DataContextPropertyAssigningVisitor();
                resolvedView.Accept(contextSpaceVisitor);

                var validationVisitor = new Validation.ControlUsageValidationVisitor(configuration);
                resolvedView.Accept(validationVisitor);
                if (validationVisitor.Errors.Any())
                {
                    var controlUsageError = validationVisitor.Errors.First();
                    throw new DotvvmCompilationException(controlUsageError.ErrorMessage, controlUsageError.Nodes.SelectMany(n => n.Tokens));
                }

                var emitter = new DefaultViewCompilerCodeEmitter();
                var compilingVisitor = new ViewCompilingVisitor(emitter, configuration.ServiceLocator.GetService <IBindingCompiler>(), className);

                resolvedView.Accept(compilingVisitor);

                return AddToCompilation(compilation, emitter, fileName, namespaceName, className);
            }
                   );
        }
Exemplo n.º 10
0
        public static DothtmlRootNode TokenizeAndParse(string dothtml)
        {
            var t = new DothtmlTokenizer();

            t.Tokenize(dothtml);
            var p = new DothtmlParser();

            return(p.Parse(t.Tokens));
        }
Exemplo n.º 11
0
        public static DothtmlRootNode ParseMarkup(string markup)
        {
            var tokenizer = new DothtmlTokenizer();

            tokenizer.Tokenize(markup);
            var parser = new DothtmlParser();
            var node   = parser.Parse(tokenizer.Tokens);

            return(node);
        }
Exemplo n.º 12
0
        /// <summary>
        /// Compiles the view and returns a function that can be invoked repeatedly. The function builds full control tree and activates the page.
        /// </summary>
        public virtual CSharpCompilation CompileView(IReader reader, string fileName, CSharpCompilation compilation, string namespaceName, string className)
        {
            // parse the document
            var tokenizer = new DothtmlTokenizer();
            tokenizer.Tokenize(reader);
            var parser = new DothtmlParser();
            var node = parser.Parse(tokenizer.Tokens);

            var resolvedView = (ResolvedTreeRoot)controlTreeResolver.ResolveTree(node, fileName);

            var errorCheckingVisitor = new ErrorCheckingVisitor();
            resolvedView.Accept(errorCheckingVisitor);

            foreach (var token in tokenizer.Tokens)
            {
                if (token.HasError && token.Error.IsCritical)
                {
                    throw new DotvvmCompilationException(token.Error.ErrorMessage, new[] { (token.Error as BeginWithLastTokenOfTypeTokenError<DothtmlToken, DothtmlTokenType>)?.LastToken ?? token });
                }
            }

            foreach (var n in node.EnumerateNodes())
            {
                if (n.HasNodeErrors)
                {
                    throw new DotvvmCompilationException(string.Join(", ", n.NodeErrors), n.Tokens);
                }
            }

            var styleVisitor = new StylingVisitor(configuration.Styles);
            resolvedView.Accept(styleVisitor);

            var validationVisitor = new Validation.ControlUsageValidationVisitor(configuration);
            resolvedView.Accept(validationVisitor);
            if (validationVisitor.Errors.Any())
            {
                var controlUsageError = validationVisitor.Errors.First();
                throw new DotvvmCompilationException(controlUsageError.ErrorMessage, controlUsageError.Nodes.SelectMany(n => n.Tokens));
            }

            if (configuration.Debug && configuration.ApplicationPhysicalPath != null)
            {
                var addExpressionDebugvisitor = new ExpressionDebugInfoAddingVisitor(Path.Combine(configuration.ApplicationPhysicalPath, fileName));
                addExpressionDebugvisitor.VisitView(resolvedView);
            }

            var emitter = new DefaultViewCompilerCodeEmitter();
            var compilingVisitor = new ViewCompilingVisitor(emitter, configuration.ServiceLocator.GetService<IBindingCompiler>(), className,
                b => configuration.ServiceLocator.GetService<IBindingIdGenerator>().GetId(b, fileName));

            resolvedView.Accept(compilingVisitor);

            return AddToCompilation(compilation, emitter, fileName, namespaceName, className);
        }
        private ResolvedTreeRoot ParseSource(string markup, string fileName = "default.dothtml")
        {
            var tokenizer = new DothtmlTokenizer();

            tokenizer.Tokenize(markup);

            var parser = new DothtmlParser();
            var tree   = parser.Parse(tokenizer.Tokens);

            return((ResolvedTreeRoot)controlTreeResolver.ResolveTree(tree, fileName));
        }
Exemplo n.º 14
0
        /// <summary>
        /// Compiles the view and returns a function that can be invoked repeatedly. The function builds full control tree and activates the page.
        /// </summary>
        public virtual (ControlBuilderDescriptor, Func <CSharpCompilation>) CompileView(string sourceCode, string fileName, CSharpCompilation compilation, string namespaceName, string className)
        {
            // parse the document
            var tokenizer = new DothtmlTokenizer();

            tokenizer.Tokenize(sourceCode);
            var parser = new DothtmlParser();
            var node   = parser.Parse(tokenizer.Tokens);

            var resolvedView = (ResolvedTreeRoot)controlTreeResolver.ResolveTree(node, fileName);

            return(new ControlBuilderDescriptor(resolvedView.DataContextTypeStack.DataContextType, resolvedView.Metadata.Type), () => {
                var errorCheckingVisitor = new ErrorCheckingVisitor();
                resolvedView.Accept(errorCheckingVisitor);

                foreach (var token in tokenizer.Tokens)
                {
                    if (token.HasError && token.Error.IsCritical)
                    {
                        throw new DotvvmCompilationException(token.Error.ErrorMessage, new[] { (token.Error as BeginWithLastTokenOfTypeTokenError <DothtmlToken, DothtmlTokenType>)?.LastToken ?? token });
                    }
                }

                foreach (var n in node.EnumerateNodes())
                {
                    if (n.HasNodeErrors)
                    {
                        throw new DotvvmCompilationException(string.Join(", ", n.NodeErrors), n.Tokens);
                    }
                }

                foreach (var visitor in config.TreeVisitors)
                {
                    visitor().ApplyAction(resolvedView.Accept).ApplyAction(v => (v as IDisposable)?.Dispose());
                }


                var validationVisitor = this.controlValidatorFactory.Invoke();
                validationVisitor.VisitAndAssert(resolvedView);

                var emitter = new DefaultViewCompilerCodeEmitter();
                var compilingVisitor = new ViewCompilingVisitor(emitter, bindingCompiler, className);

                resolvedView.Accept(compilingVisitor);

                return AddToCompilation(compilation, emitter, fileName, namespaceName, className);
            }
                   );
        }
Exemplo n.º 15
0
        private ResolvedTreeRoot ParseSource(string markup, string fileName = "default.dothtml")
        {
            var tokenizer = new DothtmlTokenizer();

            tokenizer.Tokenize(markup);

            var parser = new DothtmlParser();
            var tree   = parser.Parse(tokenizer.Tokens);

            return(controlTreeResolver.ResolveTree(tree, fileName)
                   .CastTo <ResolvedTreeRoot>()
                   .ApplyAction(new DataContextPropertyAssigningVisitor().VisitView)
                   .ApplyAction(new StylingVisitor(configuration).VisitView)
                   .ApplyAction(ActivatorUtilities.CreateInstance <ControlUsageValidationVisitor>(configuration.ServiceProvider).VisitView));
        }
Exemplo n.º 16
0
        private IAbstractTreeRoot ResolveControlTree(string filePath, DotvvmConfiguration dotvvmConfiguration)
        {
            var fileContent = File.ReadAllText(filePath, Encoding.UTF8);

            var tokenizer = new DothtmlTokenizer();

            tokenizer.Tokenize(fileContent);

            var parser   = new DothtmlParser();
            var rootNode = parser.Parse(tokenizer.Tokens);

            var treeResolver = dotvvmConfiguration.ServiceLocator.GetService <IControlTreeResolver>();

            return(treeResolver.ResolveTree(rootNode, filePath));
        }
        private IAbstractTreeRoot ResolveControlTreeUncached(string filePath)
        {
            var markupLoader = dotvvmConfig.ServiceProvider.GetService <IMarkupFileLoader>();
            var markupFile   = markupLoader.GetMarkup(dotvvmConfig, filePath);
            var fileContent  = markupFile.ContentsReaderFactory();

            var tokenizer = new DothtmlTokenizer();

            tokenizer.Tokenize(fileContent);

            var parser   = new DothtmlParser();
            var rootNode = parser.Parse(tokenizer.Tokens);

            var treeResolver = dotvvmConfig.ServiceProvider.GetService <IControlTreeResolver>();

            return(treeResolver.ResolveTree(rootNode, filePath));
        }
        protected override bool Execute(uint nCmdId, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut, NextIOleCommandTarget nextCommandTarget)
        {
            var groupId = CommandGroupId;

            if (nextCommandTarget.Execute(ref groupId, nCmdId, nCmdexecopt, pvaIn, pvaOut) == VSConstants.S_OK)
            {
                // parse the content
                var tokenizer = new DothtmlTokenizer();
                var text      = TextView.TextSnapshot.GetText();
                tokenizer.Tokenize(new StringReader(text));
                var parser = new DothtmlParser();
                var node   = parser.Parse(tokenizer.Tokens);

                // prepare the metadata control resolver
                var completionSource        = TextView.TextBuffer.Properties.GetProperty <DothtmlCompletionSource>(typeof(DothtmlCompletionSource));
                var metadataControlResolver = completionSource.MetadataControlResolver;
                metadataControlResolver.ReloadAllControls(completionSource.GetCompletionContext(null));

                try
                {
                    DTEHelper.UndoContext.Open("Format Dothtml document");
                    var edit = TextView.TextBuffer.CreateEdit(EditOptions.None, null, null);

                    // fix the casing of all elements
                    var editText = new StringBuilder(text);
                    foreach (var element in node.EnumerateNodes().OfType <DothtmlElementNode>())
                    {
                        FixElement(editText, metadataControlResolver, TextView.TextBuffer, element);
                    }
                    edit.Replace(0, editText.Length, editText.ToString());
                    edit.Apply();
                }
                finally
                {
                    DTEHelper.UndoContext.Close();
                }
            }

            return(true);
        }
Exemplo n.º 19
0
        /// <summary>
        /// Compiles the view and returns a function that can be invoked repeatedly. The function builds full control tree and activates the page.
        /// </summary>
        public virtual CSharpCompilation CompileView(IReader reader, string fileName, CSharpCompilation compilation, string namespaceName, string className)
        {
            // parse the document
            var tokenizer = new DothtmlTokenizer();

            tokenizer.Tokenize(reader);
            var parser = new DothtmlParser();
            var node   = parser.Parse(tokenizer.Tokens);

            var resolvedView = controlTreeResolver.ResolveTree(node, fileName);

            var styleVisitor = new StylingVisitor(configuration.Styles);

            resolvedView.Accept(styleVisitor);

            var emitter          = new DefaultViewCompilerCodeEmitter();
            var compilingVisitor = new ViewCompilingVisitor(emitter, configuration.ServiceLocator.GetService <IBindingCompiler>(), className,
                                                            b => configuration.ServiceLocator.GetService <IBindingIdGenerator>().GetId(b, fileName));

            resolvedView.Accept(compilingVisitor);

            return(AddToCompilation(compilation, emitter, fileName, namespaceName, className));
        }
Exemplo n.º 20
0
        public static ResolvedTreeRoot ParseResolvedTree(string markup, string fileName = "default.dothtml", DotvvmConfiguration configuration = null, bool checkErrors = true)
        {
            configuration = configuration ?? DefaultConfig;

            var tokenizer = new DothtmlTokenizer();

            tokenizer.Tokenize(markup);

            var parser = new DothtmlParser();
            var tree   = parser.Parse(tokenizer.Tokens);

            if (checkErrors)
            {
                CheckForErrors(tree);
            }

            var controlTreeResolver = configuration.ServiceProvider.GetRequiredService <IControlTreeResolver>();
            var validator           = ActivatorUtilities.CreateInstance <ControlUsageValidationVisitor>(configuration.ServiceProvider);

            return(controlTreeResolver.ResolveTree(tree, fileName)
                   .CastTo <ResolvedTreeRoot>()
                   .ApplyAction(new DataContextPropertyAssigningVisitor().VisitView)
                   .ApplyAction(x => { if (checkErrors)
                                       {
                                           CheckForErrors(x.DothtmlNode);
                                       }
                                })
                   .ApplyAction(new StylingVisitor(configuration).VisitView)
                   .ApplyAction(x => { if (checkErrors)
                                       {
                                           validator.VisitAndAssert(x);
                                       }
                                       else
                                       {
                                           validator.VisitView(x);
                                       } }));
        }
Exemplo n.º 21
0
        protected ViewCompilationResult CompileView(string fileName)
        {
            var file = fileLoader.GetMarkup(configuration, fileName);

            // parse the document
            var tokenizer = new DothtmlTokenizer();

            tokenizer.Tokenize(file.ContentsReaderFactory());
            var parser = new DothtmlParser();
            var node   = parser.Parse(tokenizer.Tokens);

            var resolvedView = (ResolvedTreeRoot)controlTreeResolver.ResolveTree(node, fileName);

            var errorCheckingVisitor = new ErrorCheckingVisitor();

            resolvedView.Accept(errorCheckingVisitor);

            foreach (var n in node.EnumerateNodes())
            {
                if (n.HasNodeErrors)
                {
                    throw new DotvvmCompilationException(string.Join(", ", n.NodeErrors), n.Tokens);
                }
            }

            var contextSpaceVisitor = new DataContextPropertyAssigningVisitor();

            resolvedView.Accept(contextSpaceVisitor);

            var styleVisitor = new StylingVisitor(configuration);

            resolvedView.Accept(styleVisitor);

            //TODO: fix usage validator
            //var validationVisitor = new ControlUsageValidationVisitor(configuration);
            //resolvedView.Accept(validationVisitor);
            //if (validationVisitor.Errors.Any())
            //{
            //    var controlUsageError = validationVisitor.Errors.First();
            //    throw new DotvvmCompilationException(controlUsageError.ErrorMessage, controlUsageError.Nodes.SelectMany(n => n.Tokens));
            //}

            DefaultViewCompilerCodeEmitter emitter = null;
            string fullClassName = null;

            if (Options.FullCompile)
            {
                var namespaceName = DefaultControlBuilderFactory.GetNamespaceFromFileName(file.FileName, file.LastWriteDateTimeUtc);
                var className     = DefaultControlBuilderFactory.GetClassFromFileName(file.FileName) + "ControlBuilder";
                fullClassName = namespaceName + "." + className;
                emitter       = new CompileTimeCodeEmitter(configuration.ServiceProvider.GetService <RefObjectSerializer>(), ObjectsClassName);
                var compilingVisitor = new ViewCompilingVisitor(emitter, configuration.ServiceProvider.GetService <IBindingCompiler>(), className);

                resolvedView.Accept(compilingVisitor);

                // compile master pages
                if (resolvedView.Directives.ContainsKey("masterPage"))
                {
                    CompileFile(resolvedView.Directives["masterPage"].Single().Value);
                }

                compilation = compilation
                              .AddSyntaxTrees(emitter.BuildTree(namespaceName, className, fileName))
                              .AddReferences(emitter.UsedAssemblies
                                             .Select(a => CompiledAssemblyCache.Instance.GetAssemblyMetadata(a.Key)));
            }

            Program2.WriteInfo($"The view { fileName } compiled successfully.");

            var res = new ViewCompilationResult {
                BuilderClassName = fullClassName,
                ControlType      = resolvedView.Metadata.Type,
                DataContextType  = emitter?.BuilderDataContextType,
                ResolvedTree     = Options.OutputResolvedDothtmlMap ? resolvedView : null
            };

            BuildFileResult(fileName, res);
            return(res);
        }
Exemplo n.º 22
0
 public static DothtmlRootNode ParseMarkup(string markup)
 {
     var tokenizer = new DothtmlTokenizer();
     tokenizer.Tokenize(new StringReader(markup));
     var parser = new DothtmlParser();
     var node = parser.Parse(tokenizer.Tokens);
     return node;
 }
        private ResolvedTreeRoot ParseSource(string markup, string fileName = "default.dothtml")
        {
            var tokenizer = new DothtmlTokenizer();
            tokenizer.Tokenize(new StringReader(markup));

            var parser = new DothtmlParser();
            var tree = parser.Parse(tokenizer.Tokens);

            return (ResolvedTreeRoot)controlTreeResolver.ResolveTree(tree, fileName);
        }
Exemplo n.º 24
0
        protected ViewCompilationResult CompileView(string fileName)
        {
            var file = fileLoader.GetMarkup(configuration, fileName);

            // parse the document
            var tokenizer = new DothtmlTokenizer();
            tokenizer.Tokenize(file.ContentsReaderFactory());
            var parser = new DothtmlParser();
            var node = parser.Parse(tokenizer.Tokens);

            var resolvedView = (ResolvedTreeRoot)controlTreeResolver.ResolveTree(node, fileName);

            var errorCheckingVisitor = new ErrorCheckingVisitor();
            resolvedView.Accept(errorCheckingVisitor);


            foreach (var n in node.EnumerateNodes())
            {
                if (n.HasNodeErrors)
                {
                    throw new DotvvmCompilationException(string.Join(", ", n.NodeErrors), n.Tokens);
                }
            }

            var styleVisitor = new StylingVisitor(configuration.Styles);
            resolvedView.Accept(styleVisitor);

            var validationVisitor = new ControlUsageValidationVisitor(configuration);
            resolvedView.Accept(validationVisitor);
            if (validationVisitor.Errors.Any())
            {
                var controlUsageError = validationVisitor.Errors.First();
                throw new DotvvmCompilationException(controlUsageError.ErrorMessage, controlUsageError.Nodes.SelectMany(n => n.Tokens));
            }

            DefaultViewCompilerCodeEmitter emitter = null;
            string fullClassName = null;
            if (Options.FullCompile)
            {
                var namespaceName = DefaultControlBuilderFactory.GetNamespaceFromFileName(file.FileName, file.LastWriteDateTimeUtc);
                var className = DefaultControlBuilderFactory.GetClassFromFileName(file.FileName) + "ControlBuilder";
                fullClassName = namespaceName + "." + className;
                emitter = new DefaultViewCompilerCodeEmitter();
                var compilingVisitor = new ViewCompilingVisitor(emitter, configuration.ServiceLocator.GetService<IBindingCompiler>(), className, b => configuration.ServiceLocator.GetService<IBindingIdGenerator>().GetId(b, fileName));

                resolvedView.Accept(compilingVisitor);

                // compile master pages
                if (resolvedView.Directives.ContainsKey("masterPage"))
                    CompileFile(resolvedView.Directives["masterPage"].Single());

                compilation = compilation
                    .AddSyntaxTrees(emitter.BuildTree(namespaceName, className, fileName)/*.Select(t => SyntaxFactory.ParseSyntaxTree(t.GetRoot().NormalizeWhitespace().ToString()))*/)
                    .AddReferences(emitter.UsedAssemblies
                        .Select(a => CompiledAssemblyCache.Instance.GetAssemblyMetadata(a)));
            }

            Program.WriteInfo($"view { fileName } compiled");

            var res = new ViewCompilationResult
            {
                BuilderClassName = fullClassName,
                ControlType = resolvedView.Metadata.Type,
                DataContextType = emitter?.BuilderDataContextType,
                ResolvedTree = Options.OutputResolvedDothtmlMap ? resolvedView : null
            };
            BuildFileResult(fileName, res);
            return res;
        }