• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

C# Ast类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中Ast的典型用法代码示例。如果您正苦于以下问题:C# Ast类的具体用法?C# Ast怎么用?C# Ast使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



Ast类属于命名空间,在下文中一共展示了Ast类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。

示例1: AnalyzeDSCResource

        /// <summary>
        /// AnalyzeDSCResource: Analyzes the ast to check that Write-Verbose is called for DSC Resources
        /// <param name="ast">The script's ast</param>
        /// <param name="fileName">The script's file name</param>
        /// </summary>
        public IEnumerable<DiagnosticRecord> AnalyzeDSCResource(Ast ast, string fileName)
        {
            if (ast == null)
            {
                throw new ArgumentNullException(Strings.NullAstErrorMessage);
            }            

            IEnumerable<Ast> functionDefinitionAsts = Helper.Instance.DscResourceFunctions(ast);

            foreach (FunctionDefinitionAst functionDefinitionAst in functionDefinitionAsts)
            {
                var commandAsts = functionDefinitionAst.Body.FindAll(testAst => testAst is CommandAst, false);
                bool hasVerbose = false;

                if (null != commandAsts)
                {
                    foreach (CommandAst commandAst in commandAsts)
                    {
                        hasVerbose |= String.Equals(commandAst.GetCommandName(), "Write-Verbose", StringComparison.OrdinalIgnoreCase);
                    }
                }

                if (!hasVerbose)
                {
                    yield return new DiagnosticRecord(string.Format(CultureInfo.CurrentCulture, Strings.UseVerboseMessageInDSCResourceErrorFunction, functionDefinitionAst.Name),
                        functionDefinitionAst.Extent, GetName(), DiagnosticSeverity.Information, fileName);
                }

            }
        }
开发者ID:AndrewGaspar,项目名称:PSScriptAnalyzer,代码行数:35,代码来源:UseVerboseMessageInDSCResource.cs


示例2: Scope

 internal Scope(IParameterMetadataProvider ast, ScopeType scopeType)
 {
     _ast = (Ast)ast;
     _scopeType = scopeType;
     _typeTable = new Dictionary<string, TypeLookupResult>(StringComparer.OrdinalIgnoreCase);
     _variableTable = new Dictionary<string, Ast>(StringComparer.OrdinalIgnoreCase);
 }
开发者ID:40a,项目名称:PowerShell,代码行数:7,代码来源:SymbolResolver.cs


示例3: AnalyzeScript

        /// <summary>
        /// MisleadingBacktick: Checks that lines don't end with a backtick followed by a whitespace
        /// </summary>
        public IEnumerable<DiagnosticRecord> AnalyzeScript(Ast ast, string fileName)
        {
            if (ast == null) throw new ArgumentNullException(Strings.NullAstErrorMessage);

            string[] lines = NewlineRegex.Split(ast.Extent.Text);

            if((ast.Extent.EndLineNumber - ast.Extent.StartLineNumber + 1) != lines.Length)
            {
                // Did not match the number of lines that the extent indicated
                yield break;
            }

            foreach (int i in Enumerable.Range(0, lines.Length))
            {
                string line = lines[i];

                Match match = TrailingEscapedWhitespaceRegex.Match(line);

                if(match.Success)
                {
                    int lineNumber = ast.Extent.StartLineNumber + i;

                    ScriptPosition start = new ScriptPosition(fileName, lineNumber, match.Index, line);
                    ScriptPosition end = new ScriptPosition(fileName, lineNumber, match.Index + match.Length, line);

                    yield return new DiagnosticRecord(
                        string.Format(CultureInfo.CurrentCulture, Strings.MisleadingBacktickError),
                            new ScriptExtent(start, end), GetName(), DiagnosticSeverity.Warning, fileName);
                }
            }
        }
开发者ID:rkeithhill,项目名称:PSScriptAnalyzer,代码行数:34,代码来源:MisleadingBacktick.cs


示例4: VisitBlockExpression

        public virtual Ast.Expression VisitBlockExpression(Ast.BlockExpression blockExpression)
        {
            foreach (var expression in blockExpression.Expressions)
                this.Visit(expression);

            return blockExpression;
        }
开发者ID:swijnands,项目名称:LinqExtender,代码行数:7,代码来源:ExpressionVisitor.cs


示例5: VisitBinaryExpression

        public virtual Ast.Expression VisitBinaryExpression(Ast.BinaryExpression expression)
        {
            this.Visit(expression.Left);
            this.Visit(expression.Right);

            return expression;
        }
开发者ID:swijnands,项目名称:LinqExtender,代码行数:7,代码来源:ExpressionVisitor.cs


示例6: VisitMethodInvocationExpression

        public override void VisitMethodInvocationExpression(Ast.Expressions.MethodInvocationExpression node)
        {
            MethodDefinition methodDef = node.MethodExpression.MethodDefinition;
            if (methodDef == null)
            {
                base.VisitMethodInvocationExpression(node);
                return;
            }

            Visit(node.MethodExpression);

            for (int i = 0; i < node.Arguments.Count; i++)
            {
                UnaryExpression unaryArgument = node.Arguments[i] as UnaryExpression;
                if (methodDef.Parameters[i].IsOutParameter() && (unaryArgument != null && unaryArgument.Operator == UnaryOperator.AddressReference &&
                     CheckExpression(unaryArgument.Operand) || CheckExpression(node.Arguments[i])))
                {
                    this.searchResult = UsageFinderSearchResult.Assigned;
                    return;
                }
                else
                {
                    Visit(node.Arguments[i]);
                    if (this.searchResult != UsageFinderSearchResult.NotFound)
                    {
                        return;
                    }
                }
            }
        }
开发者ID:besturn,项目名称:JustDecompileEngine,代码行数:30,代码来源:BaseUsageFinder.cs


示例7: AstBuilder_ComplexExpression_Build

        public void AstBuilder_ComplexExpression_Build()
        {
            var tree = new Ast("+", true);
            tree.Operands.Add(new Ast("4"));
            tree.Operands.Add(new Ast("6"));

            var buffer = new Ast("/", true);
            buffer.Operands.Add(new Ast("81"));
            buffer.Operands.Add(new Ast("-3"));

            var anotherBuffer = new Ast("*", true);
            anotherBuffer.Operands.Add(new Ast("3"));
            anotherBuffer.Operands.Add(new Ast("3"));
            buffer.Operands.Add(anotherBuffer);

            tree.Operands.Add(buffer);

            buffer = new Ast("-", true);
            buffer.Operands.Add(new Ast("10"));
            buffer.Operands.Add(new Ast("12"));

            tree.Operands.Add(buffer);
            var input = "(+ 4 6 (/ 81 -3 (* 3 3 ))( - 10 12 ))";

            var actualTree = new AstBuilder().Build(new Tokenizer().GetTokens(input));
            Assert.IsTrue(actualTree.Equals(tree));
        }
开发者ID:fanatt20,项目名称:ProgrammingTasks,代码行数:27,代码来源:AstBuilderTest.cs


示例8: AnalyzeScript

        /// <summary>
        /// AnalyzeScript: Run Test Module Manifest to check that none of the required fields are missing. From the ILintScriptRule interface.
        /// </summary>
        /// <param name="ast">The script's ast</param>
        /// <param name="fileName">The script's file name</param>
        /// <returns>A List of diagnostic results of this rule</returns>
        public IEnumerable<DiagnosticRecord> AnalyzeScript(Ast ast, string fileName)
        {
            if (ast == null) throw new ArgumentNullException(Strings.NullAstErrorMessage);

            if (String.Equals(System.IO.Path.GetExtension(fileName), ".psd1", StringComparison.OrdinalIgnoreCase))
            {
                IEnumerable<ErrorRecord> errorRecords;
                var psModuleInfo = Helper.Instance.GetModuleManifest(fileName, out errorRecords);
                if (errorRecords != null)
                {
                    foreach (var errorRecord in errorRecords)
                    {
                        if (Helper.IsMissingManifestMemberException(errorRecord))
                        {
                            System.Diagnostics.Debug.Assert(
                                errorRecord.Exception != null && !String.IsNullOrWhiteSpace(errorRecord.Exception.Message),
                                Strings.NullErrorMessage);
                            var hashTableAst = ast.Find(x => x is HashtableAst, false);
                            if (hashTableAst == null)
                            {
                                yield break;
                            }
                            yield return new DiagnosticRecord(
                                errorRecord.Exception.Message,
                                hashTableAst.Extent,
                                GetName(),
                                DiagnosticSeverity.Warning,
                                fileName,
                                suggestedCorrections:GetCorrectionExtent(hashTableAst as HashtableAst));
                        }

                    }
                }
            }
        }
开发者ID:kilasuit,项目名称:PSScriptAnalyzer,代码行数:41,代码来源:MissingModuleManifestField.cs


示例9: Compile

        public LuaFile Compile(Ast.Chunk c, string name)
        {
            file = new LuaFile();
            block = new Block();
            block.Chunk.Name = name;
            block.Chunk.ArgumentCount = 0;
            block.Chunk.Vararg = 2;

            DoChunk(c);

            file.Main = block.Chunk;
            file.Main.ArgumentCount = 0;
            file.Main.Vararg = 2;
            file.Main.UpvalueCount = file.Main.Upvalues.Count;
            bool addRet = file.Main.Instructions.Count == 0;
            if (addRet == false)
                addRet = file.Main.Instructions[file.Main.Instructions.Count - 1].Opcode != Instruction.LuaOpcode.RETURN;
            if (addRet)
            {
                Instruction ret = new Instruction("RETURN");
                ret.A = 0;
                ret.B = 1;
                ret.C = 0;
                file.Main.Instructions.Add(ret);
            }
            return file;
        }
开发者ID:zeta945,项目名称:SharpLua,代码行数:27,代码来源:Compiler3.cs


示例10: Emit

            public override void Emit(VirtualMachine.InstructionList into, Ast.OperationDestination Destination)
            {
                //Prepare loop control variables
                List.Emit(into, Ast.OperationDestination.Stack);	//[email protected]
                LengthFunc.Emit(into, Ast.OperationDestination.Stack); //[email protected]
                into.AddInstructions("MOVE NEXT PUSH # SET [email protected]", 0);			//[email protected]

                var LoopStart = into.Count;

                into.AddInstructions(
                    "LOAD_PARAMETER NEXT R #" + TotalVariable.Name, TotalVariable.Offset,
                    "GREATER_EQUAL PEEK R R #PEEK = [email protected]",
                    "IF_TRUE R",
                    "JUMP NEXT", 0);

                var BreakPoint = into.Count - 1;

                Indexer.Emit(into, Ast.OperationDestination.Stack);
                Body.Emit(into, Ast.OperationDestination.Discard);

                into.AddInstructions(
                    "MOVE POP #REMOVE [email protected]",
                    "INCREMENT PEEK PEEK",
                    "JUMP NEXT", LoopStart);

                into[BreakPoint] = into.Count;

                into.AddInstructions("CLEANUP NEXT #REMOVE [email protected], [email protected], [email protected]", 3);
            }
开发者ID:Blecki,项目名称:EtcScript,代码行数:29,代码来源:ForeachXInList.cs


示例11: AnalyzeScript

        /// <summary>
        /// AnalyzeScript: Analyzes the script to check if any non-constant members have been invoked.
        /// </summary>
        public IEnumerable<DiagnosticRecord> AnalyzeScript(Ast ast, string fileName)
        {
            if (ast == null) throw new ArgumentNullException(Strings.NullAstErrorMessage);

            IEnumerable<Ast> memberExpression = ast.FindAll(testAst => testAst is MemberExpressionAst, true);
            foreach (MemberExpressionAst member in memberExpression)
            {
                string context = member.Member.Extent.ToString();
                if (context.Contains("("))
                {
                    //check if parenthesis and have non-constant members
                    IEnumerable<Ast> binaryExpression = member.FindAll(
                        binaryAst => binaryAst is BinaryExpressionAst, true);
                    if (binaryExpression.Any())
                    {
                        foreach (BinaryExpressionAst bin in binaryExpression)
                        {
                            if (!bin.Operator.Equals(null))
                            {
                                yield return
                                    new DiagnosticRecord(
                                        string.Format(CultureInfo.CurrentCulture,
                                            Strings.AvoidInvokingEmptyMembersError,
                                            context),
                                        member.Extent, GetName(), DiagnosticSeverity.Warning, fileName);
                            }
                        }
                    }
                }
            }
        
        }
开发者ID:AndrewGaspar,项目名称:PSScriptAnalyzer,代码行数:35,代码来源:AvoidInvokingEmptyMembers.cs


示例12: ForeachIn

 public ForeachIn(Token Source, String VariableName, Ast.Node List, Ast.Node Body)
     : base(Source)
 {
     this.VariableName = VariableName;
     this.List = List;
     this.Body = Body;
 }
开发者ID:Blecki,项目名称:EtcScript,代码行数:7,代码来源:ForeachXInList.cs


示例13: Process

 public Ast.Statements.BlockStatement Process(Decompiler.DecompilationContext context, Ast.Statements.BlockStatement body)
 {
     this.methodContext = context.MethodContext;
     mappedInstructions.UnionWith(body.UnderlyingSameMethodInstructions);
     Visit(body);
     return body;
 }
开发者ID:juancarlosbaezpozos,项目名称:JustDecompileEngine,代码行数:7,代码来源:MapUnconditionalBranchesStep.cs


示例14: IsConstant

        public static bool IsConstant(Ast ast, out object constantValue, bool forAttribute = false, bool forRequires = false)
        {
            try
            {
                if ((bool)ast.Accept(new IsConstantValueVisitor { CheckingAttributeArgument = forAttribute, CheckingRequiresArgument = forRequires }))
                {
                    Ast parent = ast.Parent;
                    while (parent != null)
                    {
                        if (parent is DataStatementAst)
                        {
                            break;
                        }
                        parent = parent.Parent;
                    }

                    if (parent == null)
                    {
                        constantValue = ast.Accept(new ConstantValueVisitor { AttributeArgument = forAttribute, RequiresArgument = forRequires });
                        return true;
                    }
                }
            }
            catch (Exception e)
            {
                // If we get an exception, ignore it and assume the expression isn't constant.
                // This can happen, e.g. if a cast is invalid:
                //     [int]"zed"
                CommandProcessorBase.CheckForSevereException(e);
            }

            constantValue = null;
            return false;
        }
开发者ID:40a,项目名称:PowerShell,代码行数:34,代码来源:ConstantValues.cs


示例15: CompletionAnalysis

 internal CompletionAnalysis(Ast ast, Token[] tokens, IScriptPosition cursorPosition, Hashtable options)
 {
     _ast = ast;
     _tokens = tokens;
     _cursorPosition = cursorPosition;
     _options = options;
 }
开发者ID:dfinke,项目名称:powershell,代码行数:7,代码来源:CompletionAnalysis.cs


示例16: FindCommandAtPosition

        /// <summary>
        /// Finds the symbol (always Command type) at a given file location
        /// </summary>
        /// <param name="scriptAst">The abstract syntax tree of the given script</param>
        /// <param name="lineNumber">The line number of the cursor for the given script</param>
        /// <param name="columnNumber">The column number of the cursor for the given script</param>
        /// <returns>SymbolReference of found command</returns>
        public static SymbolReference FindCommandAtPosition(Ast scriptAst, int lineNumber, int columnNumber)
        {
            FindCommandVisitor commandVisitor = new FindCommandVisitor(lineNumber, columnNumber);
            scriptAst.Visit(commandVisitor);

            return commandVisitor.FoundCommandReference;
        }
开发者ID:juvchan,项目名称:PowerShellEditorServices,代码行数:14,代码来源:AstOperations.cs


示例17: GetSingleAstRequiredModules

        private static List<string> GetSingleAstRequiredModules(Ast ast, Token[] tokens)
        {
            List<string> modules = new List<string>();
            List<string> resources = new List<string>();
            var imports = tokens.Where(token =>
                    String.Compare(token.Text, "Import-DscResource", StringComparison.OrdinalIgnoreCase) == 0);

            //
            // Create a function with the same name as Import-DscResource keyword and use powershell
            // argument function binding to emulate Import-DscResource argument binding.
            //
            InitialSessionState initialSessionState = InitialSessionState.Create();
            SessionStateFunctionEntry importDscResourcefunctionEntry = new SessionStateFunctionEntry(
                "Import-DscResource", @"param($Name, $ModuleName)
                if ($ModuleName) 
                {
                    foreach ($m in $ModuleName) { $global:modules.Add($m) }
                } else {
                    foreach ($n in $Name) { $global:resources.Add($n) }
                }
            ");
            initialSessionState.Commands.Add(importDscResourcefunctionEntry);
            initialSessionState.LanguageMode = PSLanguageMode.RestrictedLanguage;
            var moduleVarEntry = new SessionStateVariableEntry("modules", modules, "");
            var resourcesVarEntry = new SessionStateVariableEntry("resources", resources, "");
            initialSessionState.Variables.Add(moduleVarEntry);
            initialSessionState.Variables.Add(resourcesVarEntry);

            using (System.Management.Automation.PowerShell powerShell = System.Management.Automation.PowerShell.Create(initialSessionState))
            {
                foreach (var import in imports)
                {
                    int startOffset = import.Extent.StartOffset;
                    var asts = ast.FindAll(a => IsCandidateForImportDscResourceAst(a, startOffset), true);
                    int longestLen = -1;
                    Ast longestCandidate = null;
                    foreach (var candidatAst in asts)
                    {
                        int curLen = candidatAst.Extent.EndOffset - candidatAst.Extent.StartOffset;
                        if (curLen > longestLen)
                        {
                            longestCandidate = candidatAst;
                            longestLen = curLen;
                        }
                    }
                    // longestCandidate should contain AST for import-dscresource, like "Import-DSCResource -Module x -Name y".
                    if (longestCandidate != null)
                    {
                        string importText = longestCandidate.Extent.Text;
                        // We invoke-command "importText" here. Script injection is prevented:
                        // We checked that file represents a valid AST without errors.
                        powerShell.AddScript(importText);
                        powerShell.Invoke();
                        powerShell.Commands.Clear();
                    }
                }
            }
            modules.AddRange(resources.Select(GetModuleNameForDscResource));
            return modules;
        }
开发者ID:randorfer,项目名称:azure-powershell,代码行数:60,代码来源:ConfigurationParsingHelper.cs


示例18: FindDotSourcedIncludes

        /// <summary>
        /// Finds all files dot sourced in a script
        /// </summary>
        /// <param name="scriptAst">The abstract syntax tree of the given script</param>
        /// <returns></returns>
        public static string[] FindDotSourcedIncludes(Ast scriptAst)
        {
            FindDotSourcedVisitor dotSourcedVisitor = new FindDotSourcedVisitor();
            scriptAst.Visit(dotSourcedVisitor);

            return dotSourcedVisitor.DotSourcedFiles.ToArray();
        }
开发者ID:juvchan,项目名称:PowerShellEditorServices,代码行数:12,代码来源:AstOperations.cs


示例19: Process

        public Ast.Statements.BlockStatement Process(Decompiler.DecompilationContext context, Ast.Statements.BlockStatement body)
        {
            HashSet<Instruction> mappedInstructions = new HashSet<Instruction>(body.UnderlyingSameMethodInstructions);
            if (context.MethodContext.IsMethodBodyChanged)
            {
                context.MethodContext.Method.RefreshBody();
                context.MethodContext.IsMethodBodyChanged = false;
            }

            List<Instruction> unmappedInstructions = new List<Instruction>();
            foreach (Instruction instruction in context.MethodContext.Method.Body.Instructions)
            {
                if (!mappedInstructions.Contains(instruction))
                {
                    unmappedInstructions.Add(instruction);
                }
            }

            if (unmappedInstructions.Count > 0)
            {
                StringBuilder stringBuilder = new StringBuilder("Found unmapped instructions.\n");
                foreach (Instruction unmappedInstruction in unmappedInstructions)
                {
                    stringBuilder.AppendLine(unmappedInstruction.ToString());
                }
                throw new Exception(stringBuilder.ToString());
            }

            return body;
        }
开发者ID:Feng2012,项目名称:JustDecompileEngine,代码行数:30,代码来源:InstructionMappingsCheck.cs


示例20: AnalyzeScript

        /// <summary>
        /// AnalyzeScript: Analyze the script to check if cmdlet alias is used.
        /// </summary>
        public IEnumerable<DiagnosticRecord> AnalyzeScript(Ast ast, string fileName)
        {
            if (ast == null) throw new ArgumentNullException(Strings.NullAstErrorMessage);

            // Finds all CommandAsts.
            IEnumerable<Ast> foundAsts = ast.FindAll(testAst => testAst is CommandAst, true);

            // Iterates all CommandAsts and check the command name.
            foreach (Ast foundAst in foundAsts)
            {
                CommandAst cmdAst = (CommandAst)foundAst;
                string aliasName = cmdAst.GetCommandName();

                // Handles the exception caused by commands like, {& $PLINK $args 2> $TempErrorFile}.
                // You can also review the remark section in following document,
                // MSDN: CommandAst.GetCommandName Method
                if (aliasName == null)
                {
                    continue;
                }
                string cmdletName = Helper.Instance.GetCmdletNameFromAlias(aliasName);
                if (!String.IsNullOrEmpty(cmdletName))
                {
                    yield return new DiagnosticRecord(
                        string.Format(CultureInfo.CurrentCulture, Strings.AvoidUsingCmdletAliasesError, aliasName, cmdletName),
                        cmdAst.Extent,
                        GetName(),
                        DiagnosticSeverity.Warning,
                        fileName,
                        aliasName,
                        suggestedCorrections: GetCorrectionExtent(cmdAst, cmdletName));
                }
            }
        }
开发者ID:GoFrag,项目名称:PSScriptAnalyzer,代码行数:37,代码来源:AvoidAlias.cs



注:本文中的Ast类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# AstExpression类代码示例发布时间:2022-05-24
下一篇:
C# AssociativeGraph类代码示例发布时间:2022-05-24
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap