/// <summary>Applies the css validation visitors.</summary>
        /// <param name="stylesheetNode">The stylesheet node.</param>
        /// <param name="threadContext">The thread Context.</param>
        /// <returns>The processed node.</returns>
        private AstNode ApplyValidation(AstNode stylesheetNode, IWebGreaseContext threadContext)
        {
            threadContext.SectionedAction(SectionIdParts.MinifyCssActivity, SectionIdParts.Validate).Execute(() =>
            {
                // Step # 1 - Remove the Css properties from Ast which need to be excluded (Bridging)
                if (this.ShouldExcludeProperties)
                {
                    stylesheetNode = stylesheetNode.Accept(new ExcludePropertyVisitor());
                }

                // Step # 2 - Validate for lower case
                if (this.ShouldValidateForLowerCase)
                {
                    stylesheetNode = stylesheetNode.Accept(new ValidateLowercaseVisitor());
                }

                // Step # 3 - Validate for Css hacks which don't work cross browser
                if (this.HackSelectors != null && this.HackSelectors.Any())
                {
                    stylesheetNode = stylesheetNode.Accept(new SelectorValidationOptimizationVisitor(this.HackSelectors, false, true));
                }

                // Step # 4 - Remove any banned selectors which are exposed for page efficiency
                if (this.BannedSelectors != null && this.BannedSelectors.Any())
                {
                    stylesheetNode = stylesheetNode.Accept(new SelectorValidationOptimizationVisitor(this.BannedSelectors, false, false));
                }
            });

            return(stylesheetNode);
        }
Example #2
0
        private void FillFollowPosClosure(int posOffset, AstNode inner)
        {
            var firstPosVisitor = new FirstPosGetter();

            foreach (int pos in inner.Accept(lastPosGetter, posOffset))
            {
                positions[pos].FollowPos.AddAll(inner.Accept(firstPosVisitor, posOffset));
            }
        }
Example #3
0
        public int Measure()
        {
            // we just want to measure the potential delta
            m_measure = true;
            m_delta   = 0;

            // do it and return the result
            m_expression.Accept(this);
            return(m_delta);
        }
Example #4
0
        private NFA ConvertRegexAstToNFA(AstNode root)
        {
            var visitor = new RegexToNFAVisitor();

            root.Accept(visitor);
            return(visitor.Root);
        }
Example #5
0
        public static Process CreateFromAst(AstNode n, string[] namespaces, Type[] types)
        {
            var sb = new StringBuilder();

            foreach (var ns in namespaces)
            {
                sb.AppendLine($"using {ns};");
            }
            sb.AppendLine(@"
using System;
using System.Linq;

namespace ce_toy_fx.dynamic
{
    class DynamicProcess
    {
        public static Process GetProcess()
        {
            return
            ");

            var compiler = new AstCompiler();

            n.Accept(compiler);
            sb.AppendLine(compiler.ToString());

            sb.AppendLine(@"
                .CompileToProcess(""Sample process"");
        }
    }
}
");
            return(CreateFromString(sb.ToString(), types));
        }
 public static void Apply(AstNode node)
 {
     if (node != null)
     {
         node.Accept(s_instance);
     }
 }
 public static void Apply(AstNode node)
 {
     if (node != null)
     {
         node.Accept(s_instance); 
     }
 }
Example #8
0
        public static bool NeedsParens(AstNode expression, bool outerHasNoArguments)
        {
            var visitor = new NewParensVisitor(outerHasNoArguments);

            expression.Accept(visitor);
            return(visitor.m_needsParens);
        }
Example #9
0
        public override AstNode Visit(FunctionDefinition node)
        {
            // Visit the prototype.
            AstNode proto = node.GetPrototype();

            proto.Accept(this);
            return(node);
        }
Example #10
0
        public RegularTree(AstNode root)
        {
            this.EoiCharSetNode = CharSetNode.Create(EoiChar);
            this.AugmentedRoot = new CatNode(new List<AstNode> { root, EoiCharSetNode });

            var positionBuilder = new PositionBuilder();
            AugmentedRoot.Accept(positionBuilder, null);
            Positions = positionBuilder.Positions;

            EoiPosition = Positions.FindIndex(pos => pos.Characters.Contains(EoiChar));
            Debug.Assert(EoiPosition >= 0);

            var firstPosVisitor = new FirstPosGetter();
            this.FirstPos = AugmentedRoot.Accept(firstPosVisitor, 0);

            var followPosBuilder = new FollowPosBuilder(Positions);
            AugmentedRoot.Accept(followPosBuilder, 0);
        }
        /// <summary>Applies the css optimization visitors.</summary>
        /// <param name="stylesheetNode">The stylesheet node.</param>
        /// <param name="threadContext">The thread Context.</param>
        /// <returns>The processed node.</returns>
        private AstNode ApplyOptimization(AstNode stylesheetNode, IWebGreaseContext threadContext)
        {
            // Step # 5 - Run the Css optimization visitors
            if (this.ShouldOptimize)
            {
                threadContext.SectionedAction(SectionIdParts.MinifyCssActivity, SectionIdParts.Optimize).Execute(
                    () =>
                {
                    stylesheetNode = stylesheetNode.Accept(new OptimizationVisitor {
                        ShouldMergeMediaQueries = this.ShouldMergeMediaQueries, ShouldPreventOrderBasedConflict = this.ShouldPreventOrderBasedConflict, ShouldMergeBasedOnCommonDeclarations = this.ShouldMergeBasedOnCommonDeclarations, NonMergeRuleSetSelectors = this.NonMergeSelectors
                    });
                    stylesheetNode = stylesheetNode.Accept(new ColorOptimizationVisitor());
                    stylesheetNode = stylesheetNode.Accept(new FloatOptimizationVisitor());
                });
            }

            return(stylesheetNode);
        }
Example #12
0
        private static T MakeFunc <T>(AstNode astFunction)
        {
            var generator      = new ExpressionGenerator();
            var expressionBody = astFunction.Accept(generator);
            var lambda         = Expression.Lambda <T>(expressionBody, generator.GetParameters());
            var f = lambda.Compile(DebugInfoGenerator.CreatePdbGenerator());

            return(f);
        }
Example #13
0
        /// <summary>
        /// For the given binding node, return a collection of individual INameDeclaration
        /// nodes that represent the names being declared for this binding element.
        /// </summary>
        /// <param name="node">binding node</param>
        /// <returns>collection of INameDeclaration nodes</returns>
        public static IList<BindingIdentifier> Bindings(AstNode node)
        {
            var visitor = new BindingsVisitor();
            if (node != null)
            {
                node.Accept(visitor);
            }

            return visitor.m_bindings;
        }
Example #14
0
        /// <summary>
        /// For the given binding node, return a collection of individual lookup
        /// nodes that represent the names being referenced.
        /// </summary>
        /// <param name="node">binding node</param>
        /// <returns>collection of Lookup nodes</returns>
        public static IList<LookupExpression> References(AstNode node)
        {
            var visitor = new BindingsVisitor();
            if (node != null)
            {
                node.Accept(visitor);
            }

            return visitor.m_lookups;
        }
        /// <summary>Applies the css resource visitors.</summary>
        /// <param name="stylesheetNode">The stylesheet node.</param>
        /// <param name="resources">The resources.</param>
        /// <param name="threadContext">The thread Context.</param>
        /// <returns>The processed node.</returns>
        private static AstNode ApplyResources(AstNode stylesheetNode, IEnumerable <IDictionary <string, string> > resources, IWebGreaseContext threadContext)
        {
            if (resources.Any())
            {
                threadContext.SectionedAction(SectionIdParts.MinifyCssActivity, SectionIdParts.ResourcesResolution)
                .Execute(() => { stylesheetNode = stylesheetNode.Accept(new ResourceResolutionVisitor(resources)); });
            }

            return(stylesheetNode);
        }
Example #16
0
        public static bool Apply(TextWriter writer, AstNode node, CodeSettings settings)
        {
            if (node != null)
            {
                var visitor = new JsonOutputVisitor(writer, settings);
                node.Accept(visitor);
                return(visitor.IsValid);
            }

            return(false);
        }
        public static bool Apply(TextWriter writer, AstNode node)
        {
            if (node != null)
            {
                var visitor = new JSONOutputVisitor(writer);
                node.Accept(visitor);
                return visitor.IsValid;
            }

            return false;
        }
Example #18
0
        public bool IsSafe(AstNode node)
        {
            // assume it is unless preven otherwise
            m_isSafe = true;

            if (node != null)
            {
                node.Accept(this);
            }

            return(m_isSafe);
        }
Example #19
0
        public static bool References(AstNode node, Lookup lookup)
        {
            if (node == null || lookup == null)
            {
                return(false);
            }

            var visitor = new ReferencesVisitor(lookup);

            node.Accept(visitor);
            return(visitor.m_hasReference);
        }
        public bool Query(AstNode node)
        {
            // requires by default unless a node explicitly says it doesn't need one
            DoesRequire = node != null;

            if (node != null)
            {
                node.Accept(this);
            }

            return(DoesRequire);
        }
Example #21
0
            public static IEnumerable <AstNode> Traverse(AstNode node)
            {
                yield return(node);

                foreach (var child in node.Accept(new AstChildrenVisitor()))
                {
                    foreach (var childTraverse in Traverse(child))
                    {
                        yield return(childTraverse);
                    }
                }
            }
Example #22
0
        /// <summary>Print the <see cref="AstNode"/></summary>
        /// <param name="prettyPrint">The pretty print</param>
        /// <param name="node">The node to print</param>
        /// <returns>The string representation of AST node</returns>
        internal string Print(bool prettyPrint, AstNode node)
        {
            _printerFormatter.PrettyPrint     = prettyPrint;
            _printerFormatter.IndentCharacter = IndentCharacter;
            _printerFormatter.IndentSize      = IndentSize;

            if (node != null)
            {
                node.Accept(this);
            }

            return(_printerFormatter.ToString());
        }
Example #23
0
        public RegularTree(AstNode root)
        {
            this.EoiCharSetNode = CharSetNode.Create(EoiChar);
            this.AugmentedRoot  = new CatNode(new List <AstNode> {
                root, EoiCharSetNode
            });

            var positionBuilder = new PositionBuilder();

            AugmentedRoot.Accept(positionBuilder, null);
            Positions = positionBuilder.Positions;

            EoiPosition = Positions.FindIndex(pos => pos.Characters.Contains(EoiChar));
            Debug.Assert(EoiPosition >= 0);

            var firstPosVisitor = new FirstPosGetter();

            this.FirstPos = AugmentedRoot.Accept(firstPosVisitor, 0);

            var followPosBuilder = new FollowPosBuilder(Positions);

            AugmentedRoot.Accept(followPosBuilder, 0);
        }
Example #24
0
        public void LinkProgram()
        {
            // Read the result.
            AstNode content = moduleNode;

            // Perform semantic analysis passes.
            AstVisitor[] semanticPasses = new AstVisitor[] {
                // Declare module types.
                new ModuleTypeDeclaration(),

                // Expand using <namespaces>.
                new PseudoScopeExpansion(),

                // Expand type defs.
                new TypedefExpansion(),

                // Read the object bases.
                new ModuleReadBases(),

                // Declare module object(type members)
                new ModuleObjectDeclarator(),

                // Explicit interface member binding.
                new ExplicitInterfaceBinding(),

                // Build type inheritance tables.
                new ModuleInheritance(),

                // Perform function semantic analysis.
                new FunctionSemantic(),

                // Expand constants.
                new ConstantExpansion(),

                // Generate function byte code.
                new FunctionGenerator(),
            };

            // Execute passes.
            for (int i = 0; i < semanticPasses.Length; ++i)
            {
                AstVisitor pass = semanticPasses[i];
                pass.BeginPass();
                Benchmark.Begin();
                content.Accept(pass);
                Benchmark.End(pass.GetType().ToString());
                pass.EndPass();
            }
        }
Example #25
0
 public override AstNode Visit(AstNode node)
 {
     if (node == null)
     {
         return(null);
     }
     AddDiagnostics(node);
     if (!node.Unused.IsNullOrEmpty())
     {
         foreach (var un in node.Unused)
         {
             AddDiagnostics(un);
         }
     }
     return(node.Accept(this));
 }
        public void RgbCollapse()
        {
            const string FileName       = @"RgbCollapse.css";
            AstNode      styleSheetNode = CssParser.Parse(new FileInfo(Path.Combine(ActualDirectory, FileName)));

            Assert.IsNotNull(styleSheetNode);

            styleSheetNode = styleSheetNode.Accept(new ColorOptimizationVisitor());
            Assert.IsNotNull(styleSheetNode);

            MinificationVerifier.VerifyMinification(BaseDirectory, FileName, new List <NodeVisitor> {
                new ColorOptimizationVisitor()
            });
            PrettyPrintVerifier.VerifyPrettyPrint(BaseDirectory, FileName, new List <NodeVisitor> {
                new ColorOptimizationVisitor()
            });
        }
        /// <summary>Executes the image assembly update visitor</summary>
        /// <param name="stylesheetNode">The stylesheet Ast node</param>
        /// <param name="imageLogs">The sprite Log Files.</param>
        /// <param name="dpi">The dpi.</param>
        /// <returns>The modified AST node if modified otherwise the original node</returns>
        private AstNode ExecuteImageAssemblyUpdate(AstNode stylesheetNode, IEnumerable <ImageLog> imageLogs, float dpi)
        {
            var imageAssemblyUpdateVisitor = new ImageAssemblyUpdateVisitor(
                this.SourceFile,
                imageLogs,
                dpi,
                this.OutputUnit,
                this.OutputUnitFactor,
                this.ImageBasePrefixToRemoveFromOutputPathInLog,
                this.ImageBasePrefixToAddToOutputPath,
                this.availableSourceImages,
                this.MissingImageUrl);

            stylesheetNode = stylesheetNode.Accept(imageAssemblyUpdateVisitor);

            // Return the updated Ast
            return(stylesheetNode);
        }
Example #28
0
        bool IsEqualNodes(AstNode first, AstNode second)
        {
            if (first == null)
            {
                return(second == null);
            }

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

            if (first.GetType() != second.GetType())
            {
                return(false);
            }

            _other = second;
            return(first.Accept(this));
        }
Example #29
0
        private ILCode CreateCode(string moduleName, string typeName, AstNode exp)
        {
            if (Path.GetFileName(moduleName) != moduleName)
            {
                throw new Exception("can only output into current directory!");
            }

            var             name        = new AssemblyName(Path.GetFileNameWithoutExtension(moduleName));
            AssemblyBuilder asmb        = AppDomain.CurrentDomain.DefineDynamicAssembly(name, AssemblyBuilderAccess.Save);
            ModuleBuilder   modb        = asmb.DefineDynamicModule(moduleName);
            TypeBuilder     typeBuilder = modb.DefineType(typeName);
            MethodBuilder   methMain    = typeBuilder.DefineMethod("Main", MethodAttributes.Static, typeof(void),
                                                                   Type.EmptyTypes);

            var ilcode = new ILCode {
                Type = typeBuilder, Method = methMain, Module = modb
            };

            init.CodeInfo = ilcode;
            init.GeneratePredifinedCode();

            TypeBuilder nested = AddFunctionMainToCode(ilcode, methMain);

            ilcode.Type = nested;

            ILCodeGenerator codeGenerator = new ILCodeGenerator(ilcode);

            //generacion de codigos
            exp.Accept(codeGenerator);
            ILGenerator il = methMain.GetILGenerator();

            il.Emit(OpCodes.Ret);

            nested.CreateType();
            typeBuilder.CreateType();
            modb.CreateGlobalFunctions();
            asmb.SetEntryPoint(methMain);
            asmb.Save(moduleName);

            return(ilcode);
        }
        /// <summary>Scans the css for the image path references</summary>
        /// <param name="stylesheetNode">The stylesheet node</param>
        /// <param name="threadContext">The thread Context.</param>
        /// <returns>The modified AST node if modified otherwise the original node</returns>
        private ImageAssemblyScanVisitor ExecuteImageAssemblyScan(AstNode stylesheetNode, IWebGreaseContext threadContext)
        {
            var imageAssemblyScanVisitor = new ImageAssemblyScanVisitor(
                this.SourceFile,
                this.ImageAssembleReferencesToIgnore,
                this.IgnoreImagesWithNonDefaultBackgroundSize,
                this.OutputUnit,
                this.OutputUnitFactor,
                this.availableSourceImages,
                this.MissingImageUrl,
                true)
            {
                Context = threadContext
            };

            // Scan log visitor should and does not change the stylesheet, no need to use the result.
            stylesheetNode.Accept(imageAssemblyScanVisitor);

            // return the can log results.
            return(imageAssemblyScanVisitor);
        }
Example #31
0
        public bool Match(AstNode node, string identifiers)
        {
            // set the match to false
            m_isMatch = false;

            // identifiers cannot be null or blank and must match: IDENT(.IDENT)*
            // since for JS there has to be at least a global object, the dot must be AFTER the first character.
            if (node != null && !string.IsNullOrEmpty(identifiers))
            {
                // get all the parts
                var parts = identifiers.Split('.');

                // each part must be a valid JavaScript identifier. Assume everything is valid
                // unless at least one is invalid -- then forget it
                var isValid = true;
                foreach (var part in parts)
                {
                    if (!JSScanner.IsValidIdentifier(part))
                    {
                        isValid = false;
                        break;
                    }
                }

                // must be valid to continue
                if (isValid)
                {
                    // save the parts and start the index on the last one, since we'll be walking backwards
                    m_parts = parts;
                    m_index = parts.Length - 1;

                    node.Accept(this);
                }
            }

            return(m_isMatch);
        }
        public bool Match(AstNode node, string identifiers)
        {
            // set the match to false
            m_isMatch = false;

            // identifiers cannot be null or blank and must match: IDENT(.IDENT)*
            // since for JS there has to be at least a global object, the dot must be AFTER the first character.
            if (node != null && !string.IsNullOrEmpty(identifiers))
            {
                // get all the parts
                var parts = identifiers.Split('.');

                // each part must be a valid JavaScript identifier. Assume everything is valid
                // unless at least one is invalid -- then forget it
                var isValid = true;
                foreach (var part in parts)
                {
                    if (!JSScanner.IsValidIdentifier(part))
                    {
                        isValid = false;
                        break;
                    }
                }

                // must be valid to continue
                if (isValid)
                {
                    // save the parts and start the index on the last one, since we'll be walking backwards
                    m_parts = parts;
                    m_index = parts.Length - 1;

                    node.Accept(this);
                }
            }

            return m_isMatch;
        }
 public static bool NeedsParens(AstNode expression, bool outerHasNoArguments)
 {
     var visitor = new NewParensVisitor(outerHasNoArguments);
     expression.Accept(visitor);
     return visitor.m_needsParens;
 }
 private static bool IsNullable(AstNode root)
 {
     bool result = root.Accept(NullableGetter.Instance);
     return result;
 }
        public static void Apply(AstNode node, ActivationObject scope, CodeSettings settings)
        {
            if (node != null && scope != null)
            {
                // create the visitor and run it. This will create all the child
                // scopes and populate all the scopes with the var-decl, lex-decl,
                // and lookup references within them.
                var visitor = new ResolutionVisitor(scope, settings);
                node.Accept(visitor);

                // now that all the scopes are created and they all know what decls
                // they contains, create all the fields
                CreateFields(scope);

                // now that all the fields have been created in all the scopes,
                // let's go through and resolve all the references
                ResolveLookups(scope, settings);

                // now that everything is declared and resolved as per the language specs,
                // we need to go back and add ghosted fields for older versions of IE that
                // incorrectly implement catch-variables and named function expressions.
                AddGhostedFields(scope);
            }
        }
 private CodeDomArg VisitChild(AstNode node, CodeDomArg arg)
 {
     _codeStack.Push(arg);
     node.Accept(this);
     return _codeStack.Pop();
 }
Example #37
0
 public virtual AstNode Visit(AstNode node)
 {
     return(node?.Accept(this));
 }
Example #38
0
 private object Evaluate(AstNode expr)
 {
     return(expr.Accept(this));
 }
Example #39
0
 public void Visit(AstNode node)
 {
     if (node != null)
         node.Accept(this);
 }