示例#1
0
        public SyntaxPattern Add(IFunctionDeclaration declaration)
        {
            var syntaxPattern = new SyntaxPattern(declaration);
            var overlap       = _sorted.GetViewBetween(syntaxPattern, syntaxPattern);

            switch (overlap.Count)
            {
            case 0:     // no overlap => just add it
                _sorted.Add(syntaxPattern);
                break;

            case 1:     // one overlap exists => merge with new declaration
                syntaxPattern = overlap.First();
                MergeDeclaration(syntaxPattern, declaration);
                break;

            default:     // multiple overlaps => join them to new pattern
                // overlap is a view - only valid when _sorted is not changed
                foreach (var pattern in overlap)
                {
                    foreach (var member in pattern.Members)
                    {
                        MergeDeclaration(syntaxPattern, member);
                    }
                }
                _sorted.RemoveWhere(x => x.Overlaps(syntaxPattern)); // remove existing overlaps
                _sorted.Add(syntaxPattern);                          // add the new bundle
                break;
            }
            return(syntaxPattern);
        }
示例#2
0
        /// <nodoc />
        public static bool IsReturnTypeMutable([CanBeNull] this IFunctionDeclaration function, ISemanticModel semanticModel)
        {
            if (function == null)
            {
                return(false);
            }

            var    type = function.Type;
            string name = null;

            if (type != null)
            {
                var symbol = semanticModel.GetSymbolAtLocation(type);
                name = symbol?.Name;
            }

            if (name != null)
            {
                return(IsMutable(name));
            }

            // Slow path
            var signature  = semanticModel.TypeChecker.GetSignatureFromDeclaration(function);
            var returnType = semanticModel.TypeChecker.GetReturnTypeOfSignature(signature);

            return(returnType?.IsMutable() == true);
        }
        /// <summary>
        /// http://www.ecma-international.org/ecma-262/5.1/#sec-13.2
        /// </summary>
        /// <param name="engine"></param>
        /// <param name="functionDeclaration"></param>
        /// <param name="scope"></param>
        /// <param name="strict"></param>
        public ScriptFunctionInstance(Engine engine, IFunctionDeclaration functionDeclaration, LexicalEnvironment scope, bool strict)
            : base(engine, functionDeclaration.Parameters.Select(x => x.Name).ToArray(), scope, strict)
        {
            _functionDeclaration = functionDeclaration;

            Engine     = engine;
            Extensible = true;
            Prototype  = engine.Function.PrototypeObject;

            DefineOwnProperty("length", new PropertyDescriptor(new JsValue(FormalParameters.Length), false, false, false), false);

            var proto = engine.Object.Construct(Arguments.Empty);

            proto.DefineOwnProperty("constructor", new PropertyDescriptor(this, true, false, true), false);
            DefineOwnProperty("prototype", new PropertyDescriptor(proto, true, false, false), false);
            if (_functionDeclaration.Id != null)
            {
                DefineOwnProperty("name", new PropertyDescriptor(_functionDeclaration.Id.Name, null, null, null), false);
            }

            if (strict)
            {
                var thrower = engine.Function.ThrowTypeError;
                DefineOwnProperty("caller", new PropertyDescriptor(thrower, thrower, false, false), false);
                DefineOwnProperty("arguments", new PropertyDescriptor(thrower, thrower, false, false), false);
            }
        }
示例#4
0
 public static int MandatoryRightArgumentCount(this IFunctionDeclaration declaration)
 {
     return(declaration.RightArguments.Count(
                arg =>
                !arg.IsUnrolled || // TODO: check for fixed array size
                arg.Value == null));
 }
示例#5
0
        private bool CheckBurstBannedAnalyzers(IFunctionDeclaration node)
        {
            var processor = new BurstBannedProcessor(myBurstBannedAnalyzers, node);

            node.ProcessDescendants(processor);
            return(processor.ProcessingIsFinished);
        }
        private bool CheckBurstBannedAnalyzers(IFunctionDeclaration node)
        {
            var processor = new BurstBannedProcessor(myBurstBannedAnalyzers);

            node.ProcessDescendants(processor);
            return(processor.IsBurstProhibited);
        }
示例#7
0
        static void DeclareArguments(IFunctionDeclaration function, NamedCollection <IArgumentDeclaration> arguments, ICppScope scope, string kind)
        {
            if (arguments.IsEmpty())
            {
                return;
            }
            var typeName = GetFunctionTypeName(function.Name, kind);

            scope.Declaration.AddLine($"struct {typeName} {{");
            scope.WithDeclarationIndented(
                innerScope => {
                foreach (var argument in arguments)
                {
                    var argTypeName = GetArgumentTypeName(argument.Type);
                    var argName     = CppEscape(argument.Name);
                    if (argument.IsAssignable && kind != "Result")
                    {
                        innerScope.Declaration.AddLine($"{argTypeName}* {argName};");
                        if (arguments.Count == 1)
                        {
                            innerScope.Declaration.AddLine($"operator {argTypeName}() const {{ return *{argName}; }}");
                        }
                    }
                    else
                    {
                        innerScope.Declaration.AddLine($"{argTypeName} {argName};");
                        if (arguments.Count == 1)
                        {
                            innerScope.Declaration.AddLine($"operator {argTypeName}() const {{ return {argName}; }}");
                        }
                    }
                }
            });
            scope.Declaration.AddLine(line: "};");
        }
        /// <summary>
        /// http://www.ecma-international.org/ecma-262/5.1/#sec-13.2
        /// </summary>
        /// <param name="engine"></param>
        /// <param name="functionDeclaration"></param>
        /// <param name="scope"></param>
        /// <param name="strict"></param>
        public ScriptFunctionInstance(Engine engine, IFunctionDeclaration functionDeclaration, LexicalEnvironment scope, bool strict)
            : base(engine, functionDeclaration.Parameters.Select(x => x.Name).ToArray(), scope, strict)
        {
            _functionDeclaration = functionDeclaration;

            Engine = engine;
            Extensible = true;
            Prototype = engine.Function.PrototypeObject;

            DefineOwnProperty("length", new PropertyDescriptor(new JsValue(FormalParameters.Length), false, false, false ), false);

            var proto = engine.Object.Construct(Arguments.Empty);
            proto.DefineOwnProperty("constructor", new PropertyDescriptor(this, true, false, true), false);
            DefineOwnProperty("prototype", new PropertyDescriptor(proto, true, false, false ), false);
            if (_functionDeclaration.Id != null)
            {
                DefineOwnProperty("name", new PropertyDescriptor(_functionDeclaration.Id.Name, null, null, null), false);
            }

            if (strict)
            {
                var thrower = engine.Function.ThrowTypeError;
                DefineOwnProperty("caller", new PropertyDescriptor(thrower, thrower, false, false), false);
                DefineOwnProperty("arguments", new PropertyDescriptor(thrower, thrower, false, false), false);
            }
        }
示例#9
0
 static void DeclareFunction(IFunctionDeclaration function, ICppScope scope)
 {
     DeclareArguments(function, function.LeftArguments, scope, kind: "Left");
     DeclareArguments(function, function.RightArguments, scope, kind: "Right");
     DeclareArguments(function, function.Results, scope, kind: "Result");
     DeclareFunctionBody(function, scope);
 }
示例#10
0
        //public SyntaxPattern Find(string name, int argumentCount);
        //public SyntaxPattern Find(IFunctionDeclaration declaration);

        public SyntaxPattern Add(IFunctionDeclaration declaration)
        {
            var syntax = _index.GetOrAdd(
                declaration.Name,
                () => new SyntaxPatternPool());

            return(syntax.Add(declaration));
        }
示例#11
0
 protected override void Analyze(IFunctionDeclaration t, IDaemonProcess daemonProcess, DaemonProcessKind kind,
                                 IHighlightingConsumer consumer)
 {
     if (LineMarkerStatus.Value == PerformanceHighlightingMode.Always)
     {
         consumer.AddHighlighting(new UnityPerformanceCriticalCodeLineMarker(t.GetNameDocumentRange()));
     }
 }
 protected override void Analyze(IFunctionDeclaration t,
                                 IHighlightingConsumer consumer, IReadOnlyCallGraphContext context)
 {
     if (LineMarkerStatus.Value == PerformanceHighlightingMode.Always)
     {
         consumer.AddHighlighting(new UnityPerformanceCriticalCodeLineMarker(t.GetNameDocumentRange()));
     }
 }
示例#13
0
        static IBindingLevel Create(IFunctionDeclaration declaration, Associativity associativity)
        {
            var result = new BindingLevel {
                Associaticity = associativity
            };

            // add syntax pattern
            return(result);
        }
示例#14
0
 void AssertFunctionDecl(IFunctionDeclaration expected, IFunctionDeclaration actual)
 {
     Assert.AreEqual(expected.Name, actual.Name);
     //Assert.AreEqual(expected.IsRuntimeUsable, actual.IsRuntimeUsable);
     //Assert.AreEqual(expected.IsCompileTimeUsable, actual.IsCompileTimeUsable);
     AssertArguments(expected.LeftArguments, actual.LeftArguments, name: "Left");
     AssertArguments(expected.RightArguments, actual.RightArguments, name: "Right");
     AssertArguments(expected.Results, actual.Results, name: "Results");
 }
示例#15
0
        public static bool HasSpecificAttribute(IFunctionDeclaration functionDeclaration, string name)
        {
            var declaredElement = functionDeclaration.DeclaredElement;

            if (declaredElement == null)
            {
                return(false);
            }
            return(declaredElement.GetAttributeInstances(true)
                   .Any(t => t.GetClrName().ShortName.Equals(name)));
        }
示例#16
0
        public static int?MaxRightArgumentCount(this IFunctionDeclaration declaration)
        {
            var count = declaration.RightArguments.Count;

            foreach (var argument in declaration.RightArguments)
            {
                if (argument.IsUnrolled)
                {
                    return(null);                     // TODO: check for fixed array size
                }
            }
            return(count);
        }
示例#17
0
        static void MergeDeclaration(SyntaxPattern syntaxPattern, IFunctionDeclaration declaration)
        {
            if (syntaxPattern.Members.Contains(declaration))
            {
                return;
            }

            syntaxPattern.MinArgumentCount = Math.Min(syntaxPattern.MinArgumentCount, declaration.MandatoryRightArgumentCount());
            if (syntaxPattern.MaxArgumentCount.HasValue)
            {
                var max = declaration.MaxRightArgumentCount();
                syntaxPattern.MaxArgumentCount = !max.HasValue
                    ? null
                    : (int?)Math.Max(syntaxPattern.MaxArgumentCount.Value, max.Value);
            }
            syntaxPattern.Members.Add(declaration);
        }
示例#18
0
文件: VBinaryOp.cs 项目: PShuvaev/vpl
        public VBinaryOp(IFunctionDeclaration functionDeclaration)
        {
            function = functionDeclaration;
            symbol   = functionDeclaration.name;

            firstArgPlaceHolder  = new ArgumentPlaceholder(this);
            secondArgPlaceHolder = new ArgumentPlaceholder(this);

            firstArgPlaceHolder.Parent  = this;
            secondArgPlaceHolder.Parent = this;

            OpSymbol        = new CustomLabel(symbol, BackColor);
            OpSymbol.Parent = this;

            UpdateSize();

            BackColor = ColorSettings.Get("BinaryOp");
        }
示例#19
0
        private void AnalyzeFunctionDeclaration(IFunctionDeclaration source)
        {
            var modifiers = GetModifiers(source);

            AddOrCreateDeclarationSymbol(SymbolKind.FunctionDeclaration, source.Name.Text, modifiers);

            AnalyzeDecorators(source);

            using (m_currentLocationStack.AutoPush(source.Name.Text))
            {
                AnalyzeCallSignature(source);

                if (source.Body != null)
                {
                    AnalyzeStatements(source.Body.Statements);
                }
            }
        }
示例#20
0
        public Scope CreateChildScope(IFunctionDeclaration function)
        {
            var builder = DeclaredIdentifiers.ToBuilder();

            //TODO: declarations
            //TODO: type labels

            foreach (var parameter in function.Parameters)
            {
                builder[parameter.Name] = parameter;
            }

            foreach (var variable in function.LocalVariables)
            {
                builder[variable.Name] = variable;
            }

            return(new Scope(builder.ToImmutable(), DeclaredDataTypes));
        }
示例#21
0
        /// <nodoc />
        public static bool HasMutableParameterType([CanBeNull] this IFunctionDeclaration function, ISemanticModel semanticModel)
        {
            if (function == null)
            {
                return(false);
            }

            var signature = semanticModel.TypeChecker.GetResolvedSignature(function);

            foreach (var p in signature.Parameters)
            {
                if (IsMutable(GetTypeOfSymbol(p, semanticModel)))
                {
                    return(true);
                }
            }

            return(false);
        }
示例#22
0
        static void DeclareFunctionBody(IFunctionDeclaration function, ICppScope scope)
        {
            var noResult = function.Results.IsEmpty();
            var noLeft   = function.LeftArguments.IsEmpty();
            var noRight  = function.RightArguments.IsEmpty();

            var resultType = noResult ? "void" : GetFunctionTypeName(function.Name, kind: "Result");
            var left       = string.Empty;
            var leftLocal  = string.Empty;
            var right      = string.Empty;
            var rightLocal = string.Empty;

            if (!noLeft)
            {
                leftLocal = scope.MakeLocalName(hint: "left");
                left      = GetFunctionTypeName(function.Name, kind: "Left") + " " + leftLocal;
            }
            if (!noRight)
            {
                rightLocal = scope.MakeLocalName(hint: "right");
                right      = (noLeft ? "" : ", ") + GetFunctionTypeName(function.Name, kind: "Right") + " " + rightLocal;
            }

            scope.Declaration.AddLine($"inline {resultType} {CppEscape(function.Name)}({left}{right}) {{");
            scope.WithDeclarationIndented(
                innerScope => {
                MakeArgumentLocals(function.LeftArguments, leftLocal, innerScope);
                MakeArgumentLocals(function.RightArguments, rightLocal, innerScope);
                MakeResultLocals(function.Results, innerScope);

                Dynamic(function.Implementation, innerScope);

                if (!noResult)
                {
                    var resultLocal = scope.MakeLocalName(hint: "result");
                    innerScope.Runtime.AddLine($"{resultType} {resultLocal};");
                    AssignResultsFromLocals(resultLocal, function.Results, innerScope);
                    innerScope.Runtime.AddLine($"return {resultLocal};");
                }
            });
            scope.Declaration.AddLine(line: "}");
        }
        private void ProcessFunctionDeclaration(
            IFunctionDeclaration function,
            ParserContext context)
        {
            string name;
            bool   isAnonymous = false;

            if (function.Id != null)
            {
                name = function.Id.Name;
            }
            else
            {
                name        = context.GetNameFromStack();
                isAnonymous = name.EndsWith("?");
            }

            var pars = string.Join(",",
                                   function.Parameters.Select(p => p.Name).ToArray());

            pars = pars.Shortenize(_settings.MaxParametersLength);

            var syntaxNode = (SyntaxNode)function;

            var codeNode = new CodeNode
            {
                Alias       = name + "(" + pars + ")",
                NodeType    = isAnonymous ? CodeNodeType.AnonymousFunction : CodeNodeType.Function,
                StartLine   = syntaxNode.Location.Start.Line,
                StartColumn = syntaxNode.Location.Start.Column,
                EndLine     = syntaxNode.Location.End.Line,
                EndColumn   = syntaxNode.Location.End.Column,
                Comment     = _comments.GetComment(syntaxNode.Location.Start.Line, syntaxNode.Location.End.Line)
            };

            Hierarchy <CodeNode> hi = context.Nodes.Add(codeNode);

            ProcessStatement(function.Body, new ParserContext(hi));
        }
示例#24
0
        public static bool HasAnalysisComment([CanBeNull] IFunctionDeclaration functionDeclaration, string comment, ReSharperControlConstruct.Kind status)
        {
            if (functionDeclaration == null)
            {
                return(false);
            }

            var current = functionDeclaration.PrevSibling;

            while (current is IWhitespaceNode || current is ICSharpCommentNode)
            {
                while (current is IWhitespaceNode)
                {
                    current = current.PrevSibling;
                }

                while (current is ICSharpCommentNode commentNode)
                {
                    var str           = commentNode.CommentText;
                    var configuration = ReSharperControlConstruct.ParseCommentText(str);

                    if (configuration.Kind == status)
                    {
                        foreach (var id in configuration.GetControlIds())
                        {
                            if (id == comment)
                            {
                                return(true);
                            }
                        }
                    }

                    current = current.PrevSibling;
                }
            }

            return(false);
        }
示例#25
0
 public static bool HasFrequentlyCalledMethodAttribute(IFunctionDeclaration functionDeclaration)
 {
     return(HasSpecificAttribute(functionDeclaration, "FrequentlyCalledMethodAttribute"));
 }
示例#26
0
 /// <inheritdoc />
 public override void VisitFunctionDeclaration(IFunctionDeclaration node)
 {
     m_currentReferenceKinds.Push(m_codex.FunctionScopedVariable);
     base.VisitFunctionDeclaration(node);
     m_currentReferenceKinds.Pop();
 }
示例#27
0
 private static void AnalyzeLocalFunctionDeclaration(IFunctionDeclaration source, int idx)
 {
     // Local functions are not supported
 }
 public BoundBuiltInFunctionCallExpression(IFunctionDeclaration function, IEnumerable <BoundExpression> parameters)
 {
     Function   = function;
     Parameters = parameters;
 }
示例#29
0
        public JsFunction CreateFunction(IFunctionDeclaration functionDeclaration)
        {
            JsFunction f = Global.FunctionClass.New();
            f.Statement = functionDeclaration.Statement;
            f.Name = functionDeclaration.Name;
            foreach (JsDictionaryObject scope in Scopes)
            {
                f.DeclaringScopes.Add(scope);
            }

            // add a return undefined; statement at the end of each method
            BlockStatement block = (BlockStatement)f.Statement;
            if (block.Statements.Count == 0)
            {
                block.Statements.AddLast(new ReturnStatement(new PropertyExpression(JsUndefined.TYPEOF)));
            }

            f.Arguments = functionDeclaration.Parameters;
            if (HasOption(Options.Strict))
            {
                foreach (string arg in f.Arguments)
                {
                    if (arg == "eval" || arg == "arguments")
                        throw new JsException(Global.StringClass.New("The parameters do not respect strict mode"));
                }
            }

            return f;
        }
示例#30
0
 internal FunctionInstance(IFunctionDeclaration decl)
 {
     Name        = decl.Name;
     Declaration = decl;
 }
示例#31
0
        /// <summary>
        /// Validates and Tries to extract the information function from the function
        /// </summary>
        public static bool TryExtractFunction(Logger logger, ISourceFile sourceFile, IFunctionDeclaration possibleFunction, IDictionary <string, string> lkgFiles, out TestFunction testFunction)
        {
            testFunction = null;

            var location = possibleFunction.GetLineInfo(sourceFile).ToLineAndColumn();

            var shortName = possibleFunction.Name.Text;

            var   fullName = shortName;
            INode current  = possibleFunction.Parent;

            while (current != null)
            {
                switch (current.Kind)
                {
                case SyntaxKind.SourceFile:
                case SyntaxKind.ModuleBlock:
                    current = current.Parent;
                    break;

                case SyntaxKind.ModuleDeclaration:
                    var moduleDecl = (IModuleDeclaration)current;
                    fullName = moduleDecl.Name.Text + "." + fullName;
                    current  = current.Parent;
                    break;

                default:
                    logger.LogError(sourceFile, possibleFunction, "Only top-level functions are allowed to be declared as UnitTests.");
                    return(false);
                }
            }

            if (!possibleFunction.Flags.HasFlag(NodeFlags.Export))
            {
                logger.LogError(sourceFile, possibleFunction, C($"UnitTest function '{fullName}' must be exported"));
                return(false);
            }

            if (possibleFunction.Type != null && possibleFunction.Type.Kind != SyntaxKind.VoidKeyword)
            {
                logger.LogError(sourceFile, possibleFunction, C($"UnitTest function '{fullName}' cannot return a value. It must be a 'void' function"));
                return(false);
            }

            if (possibleFunction.Parameters.Count > 0)
            {
                logger.LogError(sourceFile, possibleFunction, C($"UnitTest function '{fullName}' cannot have any parameters"));
                return(false);
            }

            if (possibleFunction.TypeParameters != null && possibleFunction.TypeParameters.Count > 0)
            {
                logger.LogError(sourceFile, possibleFunction, C($"UnitTest function '{fullName}' cannot be generic"));
                return(false);
            }

            if (possibleFunction.Body == null)
            {
                logger.LogError(sourceFile, possibleFunction, C($"UnitTest function '{fullName}' must declare a function body"));
                return(false);
            }

            string lkgFilePath = null;
            var    lkgKey      = Args.ComputeLkgKey(sourceFile.FileName, shortName);

            lkgFiles.TryGetValue(lkgKey, out lkgFilePath);

            // Remove it to mark it is already processed
            lkgFiles.Remove(lkgKey);

            testFunction = new TestFunction(shortName, fullName, location, lkgFilePath);
            return(true);
        }
示例#32
0
        public JsFunction CreateFunction(IFunctionDeclaration functionDeclaration)
        {
            JsFunction f = Global.FunctionClass.New();
            f.Statement = functionDeclaration.Statement;
            f.Name = functionDeclaration.Name;
            f.Scope = CurrentScope; // copy current scope hierarchy

            f.Arguments = functionDeclaration.Parameters;
            if (HasOption(Options.Strict)) {
                foreach (string arg in f.Arguments) {
                    if (arg == "eval" || arg == "arguments")
                        throw new JsException(Global.StringClass.New("The parameters do not respect strict mode"));
                }
            }

            return f;
        }
示例#33
0
        public JsFunction CreateFunction(IFunctionDeclaration functionDeclaration) {
            JsFunction f = Global.FunctionClass.New();

            var statementsWithDefaultReturn = new BlockStatement();
            
            // injects a default return statement at the end of each function
            statementsWithDefaultReturn.Statements.AddLast(functionDeclaration.Statement);
            statementsWithDefaultReturn.Statements.AddLast(new ReturnStatement(new Identifier("undefined")));
            f.Statement = statementsWithDefaultReturn;

            f.Name = functionDeclaration.Name;
            f.Scope = CurrentScope; // copy current scope hierarchy

            f.Arguments = functionDeclaration.Parameters;
            if (HasOption(Options.Strict)) {
                foreach (string arg in f.Arguments) {
                    if (arg == "eval" || arg == "arguments")
                        throw new JsException(Global.StringClass.New("The parameters do not respect strict mode"));
                }
            }

            return f;
        }
示例#34
0
 /// <inheritdoc />
 public override void VisitFunctionDeclaration(IFunctionDeclaration node)
 {
     Register(node, node.Flags, DocNodeType.Function, node.Name.Text, base.VisitFunctionDeclaration);
 }
        private void ProcessFunctionDeclaration(
            IFunctionDeclaration function,
            ParserContext context)
        {
            string name;
            bool isAnonymous = false;
            if (function.Id != null)
            {
                name = function.Id.Name;
            }
            else
            {
                name = context.GetNameFromStack();
                isAnonymous = name.EndsWith("?");
            }

            var pars = string.Join(",",
                function.Parameters.Select(p => p.Name).ToArray());
            pars = pars.Shortenize(_settings.MaxParametersLength);

            var syntaxNode = (SyntaxNode) function;

            var codeNode = new CodeNode
            {
                Alias = name + "(" + pars + ")",
                NodeType = isAnonymous ? CodeNodeType.AnonymousFunction : CodeNodeType.Function,
                StartLine = syntaxNode.Location.Start.Line,
                StartColumn = syntaxNode.Location.Start.Column,
                EndLine = syntaxNode.Location.End.Line,
                EndColumn = syntaxNode.Location.End.Column,
                Comment = _comments.GetComment(syntaxNode.Location.Start.Line, syntaxNode.Location.End.Line)
            };

            Hierarchy<CodeNode> hi = context.Nodes.Add(codeNode);
            ProcessStatement(function.Body, new ParserContext(hi));
        }