private static bool ParseReference(Stream stream, ShadowClass shadowClass /*, ProjectItem templateProjectItem*/)
        {
            const string keyword = "reference";

            if (stream.Current == '#' && stream.Peek() == keyword[0] && stream.PeekWord(1) == keyword)
            {
                var reference = stream.PeekLine(keyword.Length + 1);
                if (reference != null)
                {
                    var len = reference.Length + keyword.Length + 1;
                    reference = reference.Trim('"', ' ', '\n', '\r');
                    try
                    {
                        /*if (reference.EndsWith(".dll", StringComparison.OrdinalIgnoreCase))
                         *  reference = PathResolver.ResolveRelative(reference, templateProjectItem);*/

                        shadowClass.AddReference(reference);
                        return(true);
                    }
                    catch (Exception ex)
                    {
                        //Log.Error("Reference Error: " + ex);
                        Console.WriteLine($"Reference Error: {ex}");
                    }
                    finally
                    {
                        stream.Advance(len - 1);
                    }
                }
            }

            return(false);
        }
Exemplo n.º 2
0
        public Contexts(ShadowClass shadowClass)
        {
            var assembly = typeof(ContextAttribute).Assembly;

            ParseCodeModel(assembly);
            ParseExtensions(shadowClass);
        }
Exemplo n.º 3
0
 private Editor()
 {
     shadowClass   = new ShadowClass();
     contexts      = new Contexts(shadowClass);
     codeLexer     = new CodeLexer(contexts);
     templateLexer = new TemplateLexer(contexts);
 }
Exemplo n.º 4
0
        public static string Parse(string template, ref Type extensions)
        {
            if (string.IsNullOrWhiteSpace(template))
            {
                return(null);
            }

            var output      = string.Empty;
            var stream      = new Stream(template);
            var shadowClass = new ShadowClass();

            shadowClass.Clear();

            while (stream.Advance())
            {
                if (ParseCodeBlock(stream, shadowClass))
                {
                    continue;
                }
                if (ParseLambda(stream, shadowClass, ref output))
                {
                    continue;
                }
                output += stream.Current;
            }

            shadowClass.Parse();
            extensions = Compiler.Compile(shadowClass);

            return(output);
        }
Exemplo n.º 5
0
        public static string Parse(ProjectItem projectItem, string template, List <Type> extensions)
        {
            if (string.IsNullOrWhiteSpace(template))
            {
                return(null);
            }

            var output      = string.Empty;
            var stream      = new Stream(template);
            var shadowClass = new ShadowClass();
            var contexts    = new Contexts(shadowClass);

            shadowClass.Clear();

            while (stream.Advance())
            {
                if (ParseCodeBlock(stream, shadowClass))
                {
                    continue;
                }
                if (ParseLambda(stream, shadowClass, contexts, ref output))
                {
                    continue;
                }
                output += stream.Current;
            }

            shadowClass.Parse();

            extensions.Clear();
            extensions.Add(Compiler.Compile(projectItem, shadowClass));
            extensions.AddRange(FindExtensionClasses(shadowClass));

            return(output);
        }
Exemplo n.º 6
0
        public static Type Compile(ShadowClass shadowClass)
        {
            if (Directory.Exists(Constants.TempDirectory) == false)
            {
                Directory.CreateDirectory(Constants.TempDirectory);
            }

            var filname = Path.GetRandomFileName();
            var path    = Path.Combine(Constants.TempDirectory, filname);

            var result = shadowClass.Compile(path);

            if (result.Success)
            {
                return(Assembly.LoadFrom(path).GetTypes().FirstOrDefault());
            }

            var errors = result.Diagnostics.Where(diagnostic => diagnostic.IsWarningAsError || diagnostic.Severity == DiagnosticSeverity.Error);

            foreach (var error in errors)
            {
                var message = error.GetMessage();

                message = message.Replace("__Typewriter.", string.Empty);
                message = message.Replace("__Code.", string.Empty);
                message = message.Replace("publicstatic", string.Empty);

                Log.Warn("Template error: {0} {1}", error.Id, message);
            }

            throw new Exception("Failed to compile template.");
        }
Exemplo n.º 7
0
        private void ParseExtensions(ShadowClass shadowClass)
        {
            foreach (var assembly in shadowClass.ReferencedAssemblies)
            {
                var methods = assembly.GetExportedTypes().SelectMany(t => t.GetMethods(BindingFlags.Static | BindingFlags.Public)
                                                                     .Where(m => m.IsDefined(typeof(ExtensionAttribute), false) &&
                                                                            m.GetParameters().First().ParameterType.Namespace == "Typewriter.CodeModel"));

                foreach (var method in methods)
                {
                    var parameters = method.GetParameters();
                    if (parameters.Count() != 1)
                    {
                        continue;
                    }

                    var context = items.Values.FirstOrDefault(c => c.Type == parameters.First().ParameterType);

                    if (context != null)
                    {
                        var identifier = CreateIdentifier(method);
                        context.AddExtensionIdentifier(method.ReflectedType.Namespace, identifier);
                    }
                }
            }
        }
        private static bool ParseCodeBlock(Stream stream, ShadowClass shadowClass)
        {
            if (stream.Current == '$' && stream.Peek() == '{')
            {
                for (var i = 0; ; i--)
                {
                    var current = stream.Peek(i);
                    if (current == '`' || (current == '/' && stream.Peek(i - 1) == '/'))
                    {
                        return(false);
                    }
                    if (current == '\n' || current == char.MinValue)
                    {
                        break;
                    }
                }

                stream.Advance();

                var block      = stream.PeekBlock(1, '{', '}');
                var codeStream = new Stream(block, stream.Position + 1);

                ParseUsings(codeStream, shadowClass);
                ParseCode(codeStream, shadowClass);

                stream.Advance(block.Length + 1);

                return(true);
            }

            return(false);
        }
Exemplo n.º 9
0
 private Editor()
 {
     shadowClass        = new ShadowClass();
     contexts           = new Contexts(shadowClass);
     _codeLexerTst      = new CodeLexer(contexts);
     _codeLexerTstX     = new TstXCodeLexer(contexts);
     _templateLexerTst  = new TemplateLexer(contexts);
     _templateLexerTstX = new TstXTemplateLexer(contexts);
 }
        private static bool ParseLambda(Stream stream, ShadowClass shadowClass, Contexts contexts, ref string template)
        {
            if (stream.Current == '$')
            {
                var identifier = stream.PeekWord(1);
                if (identifier != null)
                {
                    var filter = stream.PeekBlock(identifier.Length + 2, '(', ')');
                    if (filter != null && stream.Peek(filter.Length + 2 + identifier.Length + 1) == '[')
                    {
                        try
                        {
                            var index = filter.IndexOf("=>", StringComparison.Ordinal);

                            if (index > 0)
                            {
                                var name = filter.Substring(0, index);

                                var contextName = identifier;
                                // Todo: Make the TemplateCodeParser context aware
                                if (contextName == "TypeArguments")
                                {
                                    contextName = "Types";
                                }
                                else if (contextName.StartsWith("Nested"))
                                {
                                    contextName = contextName.Remove(0, 6);
                                }

                                var type = contexts.Find(contextName)?.Type.FullName;

                                if (type == null)
                                {
                                    return(false);
                                }

                                var methodIndex = _counter++;

                                shadowClass.AddLambda(filter, type, name, methodIndex);

                                stream.Advance(filter.Length + 2 + identifier.Length);
                                template += $"${identifier}($__{methodIndex})";

                                return(true);
                            }
                        }
                        catch
                        {
                            //ignored
                        }
                    }
                }
            }

            return(false);
        }
Exemplo n.º 11
0
        public static Type Compile(ProjectItem projectItem, ShadowClass shadowClass)
        {
            if (Directory.Exists(Constants.TempDirectory) == false)
            {
                Directory.CreateDirectory(Constants.TempDirectory);
            }

            var filname = Path.GetRandomFileName();
            var path    = Path.Combine(Constants.TempDirectory, filname);

            var result = shadowClass.Compile(path);

            ErrorList.Clear();

            var errors = result.Diagnostics.Where(diagnostic => diagnostic.Severity == DiagnosticSeverity.Error || diagnostic.Severity == DiagnosticSeverity.Warning);

            var hasErrors = false;

            foreach (var error in errors)
            {
                var message = error.GetMessage();

                message = message.Replace("__Typewriter.", string.Empty);
                //message = message.Replace("__Code.", string.Empty);
                message = message.Replace("publicstatic", string.Empty);

                Log.Warn("Template error: {0} {1}", error.Id, message);

                if (error.Severity == DiagnosticSeverity.Error || error.IsWarningAsError)
                {
                    ErrorList.AddError(projectItem, message);
                    hasErrors = true;
                }
                else
                {
                    ErrorList.AddWarning(projectItem, message);
                }
            }

            if (hasErrors)
            {
                ErrorList.Show();
            }

            if (result.Success)
            {
                var assembly = Assembly.LoadFrom(path);
                var type     = assembly.GetType("__Typewriter.Template");

                return(type);
            }

            throw new Exception("Failed to compile template.");
        }
Exemplo n.º 12
0
        private static void ParseCode(Stream stream, ShadowClass shadowClass)
        {
            var code = new StringBuilder();

            do
            {
                code.Append(stream.Current);
            }while (stream.Advance());

            shadowClass.AddBlock(code.ToString(), 0);
        }
Exemplo n.º 13
0
        private static bool ParseCodeBlock(Stream stream, ShadowClass shadowClass)
        {
            if (stream.Current == '$' && stream.Peek() == '{')
            {
                stream.Advance();

                var block      = stream.PeekBlock(1, '{', '}');
                var codeStream = new Stream(block, stream.Position + 1);

                ParseUsings(codeStream, shadowClass);
                ParseCode(codeStream, shadowClass);

                stream.Advance(block.Length + 1);

                return(true);
            }

            return(false);
        }
        private static void ParseUsings(Stream stream, ShadowClass shadowClass)
        {
            stream.Advance();

            while (true)
            {
                stream.SkipWhitespace();

                if ((stream.Current == 'u' && stream.PeekWord() == "using") || (stream.Current == '/' && stream.Peek() == '/'))
                {
                    var line = stream.PeekLine();
                    shadowClass.AddUsing(line, stream.Position);
                    stream.Advance(line.Length);

                    continue;
                }

                break;
            }
        }
        private static IEnumerable <Type> FindExtensionClasses(ShadowClass shadowClass)
        {
            var types = new List <Type>();

            var usings = shadowClass.Snippets.Where(s => s.Type == SnippetType.Using && s.Code.StartsWith("using"));

            foreach (var usingStatement in usings.Select(u => u.Code))
            {
                var ns = usingStatement.Remove(0, 5).Trim().Trim(';');

                foreach (var assembly in shadowClass.ReferencedAssemblies)
                {
                    types.AddRange(assembly.GetExportedTypes().Where(t => t.Namespace == ns &&
                                                                     t.GetMethods(BindingFlags.Static | BindingFlags.Public).Any(m =>
                                                                                                                                 m.IsDefined(typeof(ExtensionAttribute), false) &&
                                                                                                                                 m.GetParameters().First().ParameterType.Namespace == "Typewriter.CodeModel")));
                }
            }

            return(types);
        }
 public SemanticModel(ShadowClass shadowClass)
 {
     _shadowClass = shadowClass;
 }
Exemplo n.º 17
0
        public static Type Compile(ShadowClass shadowClass)
        {
            if (Directory.Exists(Constants.TempDirectory) == false)
            {
                Directory.CreateDirectory(Constants.TempDirectory);
            }

            Assembly asm;
            var      cachePath = Path.Combine(Constants.TempDirectory, Sha256(shadowClass.Source) + ".bin");

            if (!File.Exists(cachePath))
            {
                foreach (Assembly assembly in shadowClass.ReferencedAssemblies)
                {
                    if (assembly.GlobalAssemblyCache)
                    {
                        continue;
                    }

                    var asmSourcePath = assembly.Location;
                    var asmDestPath   = Path.Combine(Constants.TempDirectory, Path.GetFileName(asmSourcePath));
                    try
                    {
                        //File may be in use
                        File.Copy(asmSourcePath, asmDestPath, true);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine($"Warn: {e}");
                        //Log.Warn(e.ToString());
                    }
                }

                var filname = Path.GetRandomFileName();
                var path    = Path.Combine(Constants.TempDirectory, filname);

                var result = shadowClass.Compile(path);

                //ErrorList.Clear();

                var errors = result.Diagnostics.Where(diagnostic =>
                                                      diagnostic.Severity == DiagnosticSeverity.Error ||
                                                      diagnostic.Severity == DiagnosticSeverity.Warning);

                foreach (var error in errors)
                {
                    var message = error.GetMessage();

                    message = message.Replace("__Typewriter.", string.Empty);
                    //message = message.Replace("__Code.", string.Empty);
                    message = message.Replace("publicstatic", string.Empty);

                    //Log.Warn("Template error: {0} {1}", error.Id, message);
                    Console.WriteLine("Template error: {0} {1}", error.Id, message);

                    if (error.Severity == DiagnosticSeverity.Error || error.IsWarningAsError)
                    {
                        Console.WriteLine("Error: {0}", message);
                        //ErrorList.AddError(projectItem, message);
                    }
                    else
                    {
                        //ErrorList.AddWarning(projectItem, message);
                        Console.WriteLine($"Warn: {message}");
                    }
                }

//            if (hasErrors)
//                ErrorList.Show();

                if (!result.Success)
                {
                    throw new InvalidOperationException("Template compilation errors.");
                }
                asm = Assembly.LoadFrom(path);
                File.Move(path, cachePath);
            }
            else
            {
                asm = Assembly.Load(File.ReadAllBytes(cachePath));
            }
            var type = asm.GetType("__Typewriter.Template");

            return(type);
        }
Exemplo n.º 18
0
 public SemanticModel(ShadowClass shadowClass)
 {
     this.shadowClass = shadowClass;
 }
Exemplo n.º 19
0
        public static Type Compile(ProjectItem projectItem, ShadowClass shadowClass)
        {
            if (Directory.Exists(Constants.TempDirectory) == false)
            {
                Directory.CreateDirectory(Constants.TempDirectory);
            }

            foreach (Assembly assembly in shadowClass.ReferencedAssemblies)
            {
                if (assembly.GlobalAssemblyCache)
                {
                    continue;
                }

                var asmSourcePath = assembly.Location;
                var asmDestPath   = Path.Combine(Constants.TempDirectory, Path.GetFileName(asmSourcePath));

                var          sourceAssemblerInfo = AssemblyName.GetAssemblyName(asmSourcePath);
                AssemblyName destAssemblerInfo   = null;

                // Ignores the Assembler if versions are equals.
                if (File.Exists(asmDestPath))
                {
                    destAssemblerInfo = AssemblyName.GetAssemblyName(asmDestPath);
                    if (sourceAssemblerInfo.Version.CompareTo(destAssemblerInfo.Version) == 0)
                    {
                        continue;
                    }
                }

                try
                {
                    //File may be in use
                    File.Copy(asmSourcePath, asmDestPath, true);
                }
                catch (Exception e)
                {
                    Log.Warn($"{e.ToString()} \r\n  Source Version {sourceAssemblerInfo.Version}, Target Verison  {destAssemblerInfo?.Version.ToString() ?? "None"} ");
                }
            }

            var filname = Path.GetRandomFileName();
            var path    = Path.Combine(Constants.TempDirectory, filname);

            var result = shadowClass.Compile(path);

            ErrorList.Clear();

            var errors = result.Diagnostics.Where(diagnostic => diagnostic.Severity == DiagnosticSeverity.Error || diagnostic.Severity == DiagnosticSeverity.Warning);

            var hasErrors = false;

            foreach (var error in errors)
            {
                var message = error.GetMessage();

                message = message.Replace("__Typewriter.", string.Empty);
                //message = message.Replace("__Code.", string.Empty);
                message = message.Replace("publicstatic", string.Empty);

                Log.Warn("Template error: {0} {1}", error.Id, message);

                if (error.Severity == DiagnosticSeverity.Error || error.IsWarningAsError)
                {
                    ErrorList.AddError(projectItem, message);
                    hasErrors = true;
                }
                else
                {
                    ErrorList.AddWarning(projectItem, message);
                }
            }

            if (hasErrors)
            {
                ErrorList.Show();
            }

            if (result.Success)
            {
                var assembly = Assembly.LoadFrom(path);
                var type     = assembly.GetType("__Typewriter.Template");

                return(type);
            }

            throw new Exception("Failed to compile template.");
        }