コード例 #1
0
    public AssemblyBytes(Stream s)
    {
        node = s.ReadClass(ref FileFormat);

        // Widen any nodes to the width of their children
        node.CallBack(n =>
        {
            if (n.Children.Any())
            {
                n.Start = Math.Min(n.Start, n.Children.Min(c => c.Start));
                n.End = Math.Max(n.End, n.Children.Max(c => c.End));
            }
        });

        // Order child nodes by index, expected for Heaps and sections
        node.CallBack(n =>
        {
            n.Children = n.Children.OrderBy(c => c.Start).ToList();
        });

        FindOverLength(s, node);

        node.CallBack(n => n.UseDelayedValueNode());

        node.AssignPath();
        node.CallBack(CodeNode.AssignLink);
    }
コード例 #2
0
ファイル: Script.cs プロジェクト: modulexcite/NiL.JS
 /// <summary>
 /// Инициализирует объект типа Script и преобрзует код сценария во внутреннее представление.
 /// </summary>
 /// <param name="code">Код скрипта на языке JavaScript.</param>
 /// <param name="parentContext">Родительский контекст для контекста выполнения сценария.</param>
 /// <param name="messageCallback">Делегат обратного вызова, используемый для вывода сообщений компилятора</param>
 public Script(string code, Context parentContext, CompilerMessageCallback messageCallback, Options options)
 {
     if (code == null)
         throw new ArgumentNullException();
     Code = code;
     int i = 0;
     root = CodeBlock.Parse(new ParsingState(Tools.RemoveComments(code, 0), Code, messageCallback), ref i).Statement;
     if (i < code.Length)
         throw new System.ArgumentException("Invalid char");
     CompilerMessageCallback icallback = messageCallback != null ? (level, cord, message) =>
         {
             messageCallback(level, CodeCoordinates.FromTextPosition(code, cord.Column, cord.Length), message);
         } : null as CompilerMessageCallback;
     var stat = new FunctionStatistics();
     Parser.Build(ref root, 0, new System.Collections.Generic.Dictionary<string, VariableDescriptor>(), _BuildState.None, icallback, stat, options);
     var body = root as CodeBlock;
     Context = new Context(parentContext ?? NiL.JS.Core.Context.globalContext, true, pseudoCaller);
     Context.thisBind = new GlobalObject(Context);
     Context.variables = (root as CodeBlock).variables;
     Context.strict = (root as CodeBlock).strict;
     for (i = body.localVariables.Length; i-- > 0; )
     {
         var f = Context.DefineVariable(body.localVariables[i].name);
         body.localVariables[i].cacheRes = f;
         body.localVariables[i].cacheContext = Context;
         if (body.localVariables[i].Inititalizator != null)
             f.Assign(body.localVariables[i].Inititalizator.Evaluate(Context));
         if (body.localVariables[i].isReadOnly)
             body.localVariables[i].cacheRes.attributes |= JSObjectAttributesInternal.ReadOnly;
         body.localVariables[i].captured |= stat.ContainsEval;
     }
     var bd = body as CodeNode;
     body.Optimize(ref bd, null, icallback, options, stat);
 }
コード例 #3
0
 internal static ParseResult Parse(ParsingState state, ref int index)
 {
     int i = index;
     while (char.IsWhiteSpace(state.Code[i])) i++;
     if (!Parser.Validate(state.Code, "do", ref i) || !Parser.isIdentificatorTerminator(state.Code[i]))
         return new ParseResult();
     int labelsCount = state.LabelCount;
     state.LabelCount = 0;
     while (char.IsWhiteSpace(state.Code[i])) i++;
     state.AllowBreak.Push(true);
     state.AllowContinue.Push(true);
     int ccs = state.continiesCount;
     int cbs = state.breaksCount;
     var body = Parser.Parse(state, ref i, 4);
     if (body is FunctionExpression)
     {
         if (state.strict.Peek())
             throw new JSException((new NiL.JS.BaseLibrary.SyntaxError("In strict mode code, functions can only be declared at top level or immediately within another function.")));
         if (state.message != null)
             state.message(MessageLevel.CriticalWarning, CodeCoordinates.FromTextPosition(state.Code, body.Position, body.Length), "Do not declare function in nested blocks.");
         body = new CodeBlock(new[] { body }, state.strict.Peek()); // для того, чтобы не дублировать код по декларации функции, 
         // она оборачивается в блок, который сделает самовыпил на втором этапе, но перед этим корректно объявит функцию.
     }
     state.AllowBreak.Pop();
     state.AllowContinue.Pop();
     if (!(body is CodeBlock) && state.Code[i] == ';')
         i++;
     while (i < state.Code.Length && char.IsWhiteSpace(state.Code[i])) i++;
     if (i >= state.Code.Length)
         throw new JSException(new SyntaxError("Unexpected end of source."));
     if (!Parser.Validate(state.Code, "while", ref i))
         throw new JSException((new SyntaxError("Expected \"while\" at + " + CodeCoordinates.FromTextPosition(state.Code, i, 0))));
     while (char.IsWhiteSpace(state.Code[i])) i++;
     if (state.Code[i] != '(')
         throw new JSException((new SyntaxError("Expected \"(\" at + " + CodeCoordinates.FromTextPosition(state.Code, i, 0))));
     do i++; while (char.IsWhiteSpace(state.Code[i]));
     var condition = Parser.Parse(state, ref i, 1);
     while (char.IsWhiteSpace(state.Code[i])) i++;
     if (state.Code[i] != ')')
         throw new JSException((new SyntaxError("Expected \")\" at + " + CodeCoordinates.FromTextPosition(state.Code, i, 0))));
     i++;
     var pos = index;
     index = i;
     return new ParseResult()
     {
         IsParsed = true,
         Statement = new DoWhileStatement()
         {
             allowRemove = ccs == state.continiesCount && cbs == state.breaksCount,
             body = body,
             condition = condition,
             labels = state.Labels.GetRange(state.Labels.Count - labelsCount, labelsCount).ToArray(),
             Position = pos,
             Length = index - pos
         }
     };
 }
コード例 #4
0
    static void FindOverLength(Stream s, CodeNode node)
    {
        long? length = null;
        try
        {
            length = s.Length;
        }
        catch
        { }

        if (length.HasValue)
        {
            node.CallBack(n =>
            {
                if (n.End > length)
                {
                    throw new InvalidOperationException($"End was set beyond byte end to {n.End}");
                }
            });
        }
    }
コード例 #5
0
        static void AssertInterestingBytesNotIgnored(CodeNode node, byte[] data)
        {
            if (!node.Children.Any())
            {
                return;
            }

            HashSet<int> childIncludes = new HashSet<int>();
            foreach (var child in node.Children)
            {
                childIncludes.UnionWith(new HashSet<int>(Enumerable.Range(child.Start, child.End - child.Start)));
            }

            foreach (var i in Enumerable.Range(node.Start, node.End - node.Start))
            {
                if (data[i] == 0 || childIncludes.Contains(i))
                    continue;

                Assert.Fail($"Interesting byte 0x{data[i]:X} at 0x{i:X} was non-zero in node {node.Name}");
            }
        }
コード例 #6
0
ファイル: Break.cs プロジェクト: viceice/NiL.JS
 public override void Decompose(ref CodeNode self)
 {
 }
コード例 #7
0
ファイル: TryCatch.cs プロジェクト: v1rusw0rm/NiL.JS
        internal static CodeNode Parse(ParseInfo state, ref int index)
        {
            int i = index;

            if (!Parser.Validate(state.Code, "try", ref i) || !Parser.IsIdentifierTerminator(state.Code[i]))
            {
                return(null);
            }
            while (i < state.Code.Length && Tools.IsWhiteSpace(state.Code[i]))
            {
                i++;
            }
            if (i >= state.Code.Length)
            {
                ExceptionHelper.Throw(new SyntaxError("Unexpected end of line."));
            }
            if (state.Code[i] != '{')
            {
                ExceptionHelper.Throw((new SyntaxError("Invalid try statement definition at " + CodeCoordinates.FromTextPosition(state.Code, i, 0))));
            }
            var b = CodeBlock.Parse(state, ref i);

            while (Tools.IsWhiteSpace(state.Code[i]))
            {
                i++;
            }
            CodeNode cb    = null;
            string   exptn = null;

            if (Parser.Validate(state.Code, "catch (", ref i) || Parser.Validate(state.Code, "catch(", ref i))
            {
                Tools.SkipSpaces(state.Code, ref i);

                int s = i;
                if (!Parser.ValidateName(state.Code, ref i, state.strict))
                {
                    ExceptionHelper.Throw((new SyntaxError("Catch block must contain variable name " + CodeCoordinates.FromTextPosition(state.Code, i, 0))));
                }

                exptn = Tools.Unescape(state.Code.Substring(s, i - s), state.strict);
                if (state.strict)
                {
                    if (exptn == "arguments" || exptn == "eval")
                    {
                        ExceptionHelper.Throw((new SyntaxError("Varible name can not be \"arguments\" or \"eval\" in strict mode at " + CodeCoordinates.FromTextPosition(state.Code, s, i - s))));
                    }
                }

                Tools.SkipSpaces(state.Code, ref i);

                if (!Parser.Validate(state.Code, ")", ref i))
                {
                    ExceptionHelper.Throw((new SyntaxError("Expected \")\" at + " + CodeCoordinates.FromTextPosition(state.Code, i, 0))));
                }
                while (Tools.IsWhiteSpace(state.Code[i]))
                {
                    i++;
                }
                if (state.Code[i] != '{')
                {
                    ExceptionHelper.Throw((new SyntaxError("Invalid catch block statement definition at " + CodeCoordinates.FromTextPosition(state.Code, i, 0))));
                }
                state.lexicalScopeLevel++;
                try
                {
                    cb = CodeBlock.Parse(state, ref i);
                }
                finally
                {
                    state.lexicalScopeLevel--;
                }
                while (i < state.Code.Length && Tools.IsWhiteSpace(state.Code[i]))
                {
                    i++;
                }
            }
            CodeNode f = null;

            if (Parser.Validate(state.Code, "finally", i) && Parser.IsIdentifierTerminator(state.Code[i + 7]))
            {
                i += 7;
                while (Tools.IsWhiteSpace(state.Code[i]))
                {
                    i++;
                }
                if (state.Code[i] != '{')
                {
                    ExceptionHelper.Throw((new SyntaxError("Invalid finally block statement definition at " + CodeCoordinates.FromTextPosition(state.Code, i, 0))));
                }
                f = CodeBlock.Parse(state, ref i);
            }
            if (cb == null && f == null)
            {
                ExceptionHelper.ThrowSyntaxError("try block must contain 'catch' or/and 'finally' block", state.Code, index);
            }

            var pos = index;

            index = i;
            return(new TryCatch()
            {
                body = (CodeBlock)b,
                catchBody = (CodeBlock)cb,
                finallyBody = (CodeBlock)f,
                catchVariableDesc = new VariableDescriptor(exptn, state.lexicalScopeLevel + 1),
                Position = pos,
                Length = index - pos
            });
        }
コード例 #8
0
 static NativeXCodeParser()
 {
     tokenizer = new NativeXTokenizer();
     CodeNode.Preload(typeof(NativeXUnit).Assembly);
 }
コード例 #9
0
        private void ProcessExpression(Expression exp, ParserContext context)
        {
            if (exp == null)
            {
                return;
            }

            if (exp is BinaryExpression)
            {
                var bexp = exp.As<BinaryExpression>();

                ProcessExpression(bexp.Left, context);

                ProcessExpression(bexp.Right, context);
                return;
            }

            if (exp is CallExpression)
            {
                var invexp = exp.As<CallExpression>();
                ProcessExpression(invexp.Callee, context);

                foreach (var arg in invexp.Arguments)
                {
                    var cc = new ParserContext(context, copyNames: true);
                    cc.NameStack.Insert(0, "?");
                    ProcessExpression(arg, cc);
                }
                return;
            }

            if (exp is UnaryExpression)
            {
                var uexp = (UnaryExpression)exp;
                ProcessExpression(uexp.Argument, context);
                return;
            }

            if (exp is IFunctionDeclaration)
            {
                ProcessFunctionDeclaration((IFunctionDeclaration)exp, context);
                return;
            }

            if (exp is ObjectExpression)
            {
                var ojexp = (ObjectExpression)exp;

                if (ojexp.Properties.Any())
                {
                    var codeNode = new CodeNode
                    {
                        Alias = context.GetNameFromStack(),
                        NodeType = CodeNodeType.Object,
                        StartLine = exp.Location.Start.Line,
                        StartColumn = exp.Location.Start.Column,
                        EndLine = exp.Location.End.Line,
                        EndColumn = exp.Location.End.Column,
                        Comment = _comments.GetComment(exp.Location.Start.Line, exp.Location.End.Line)
                    };
                    Hierarchy<CodeNode> hi = context.Nodes.Add(codeNode);

                    foreach (var element in ojexp.Properties)
                    {
                        var childContext = new ParserContext(hi);
                        ProcessExpression((Expression)element.Key, childContext);
                        ProcessExpression(element.Value, childContext);
                    }
                }

                return;
            }

            if (exp is AssignmentExpression)
            {
                var qexp = (AssignmentExpression)exp;
                ProcessExpression(qexp.Left, context);
                ProcessExpression(qexp.Right, context);
                return;
            }

            if (exp is Identifier)
            {
                var iexp = (Identifier)exp;
                context.NameStack.Push(iexp.Name);
                return;
            }

            if (exp is Literal)
            {
                var slexp = (Literal)exp;
                context.NameStack.Push(slexp.Raw);
                return;
            }

            if (exp is MemberExpression)
            {
                var mexp = exp.As<MemberExpression>();
                ProcessExpression(mexp.Property, context);
                ProcessExpression(mexp.Object, new ParserContext(context));
                return;
            }

            if (exp is ArrayExpression)
            {
                var arexp = exp.As<ArrayExpression>();
                foreach (var arelt in arexp.Elements)
                {
                    ProcessExpression(arelt, new ParserContext(context));
                }
            }

            if (exp is NewExpression)
            {
                var nexp = exp.As<NewExpression>();
                foreach (var elt in nexp.Arguments)
                {
                    ProcessExpression(elt, new ParserContext(context.Nodes));
                }
            }

            if (exp is LogicalExpression)
            {
                var lexp = exp.As<LogicalExpression>();
                ProcessExpression(lexp.Left, new ParserContext(context, copyNames: true));
                ProcessExpression(lexp.Right, new ParserContext(context, copyNames: true));
            }

            return;
        }
コード例 #10
0
ファイル: NavigationTreeView.cs プロジェクト: hxhlb/jsparser
        private TreeNode SearchNode(TreeNodeCollection nodes, CodeNode cn)
        {
            foreach (CustomTreeNode node in nodes)
            {
                if (node.CodeNode == cn)
                {
                    return node;
                }

                var inner = SearchNode(node.Nodes, cn);

                if (inner != null)
                {
                    return inner;
                }
            }

            return null;
        }
コード例 #11
0
 internal override void Optimize(ref CodeNode _this, FunctionExpression owner, CompilerMessageCallback message, Options opts, FunctionStatistics statistic)
 {
     // do nothing
 }
コード例 #12
0
ファイル: CodeBlock.cs プロジェクト: toolgood/NiL.JS
        public override bool Build(ref CodeNode _this, int expressionDepth, Dictionary <string, VariableDescriptor> variables, CodeContext codeContext, InternalCompilerMessageCallback message, FunctionInfo stats, Options opts)
        {
            if (built)
            {
                return(false);
            }
            built = true;

            List <VariableDescriptor> variablesToRestore = null;

            if (_variables != null && _variables.Length != 0)
            {
                for (var i = 0; i < _variables.Length; i++)
                {
                    VariableDescriptor desc = null;
                    if (variables.TryGetValue(_variables[i].name, out desc) && desc.definitionScopeLevel < _variables[i].definitionScopeLevel)
                    {
                        if (variablesToRestore == null)
                        {
                            variablesToRestore = new List <VariableDescriptor>();
                        }
                        variablesToRestore.Add(desc);
                    }

                    variables[_variables[i].name] = _variables[i];

                    _variables[i].owner = this;
                }

                for (var i = 0; i < _variables.Length; i++)
                {
                    Parser.Build(
                        ref _variables[i].initializer,
                        System.Math.Max(2, expressionDepth),
                        variables,
                        codeContext | (_strict ? CodeContext.Strict : CodeContext.None),
                        message,
                        stats,
                        opts);
                }
            }

            var lastRealExp = 0;

            for (var i = 0; i < _lines.Length; i++)
            {
                var ed = _lines[i] as EntityDefinition;
                if (ed != null && ed.Hoist)
                {
                    _lines[i] = null;
                }
                else
                {
                    lastRealExp = i;
                }
            }

            bool unreachable = false;

            for (int i = 0; i < _lines.Length; i++)
            {
                if (_lines[i] != null)
                {
                    if (_lines[i] is Empty)
                    {
                        _lines[i] = null;
                    }
                    else
                    {
                        if (unreachable && message != null)
                        {
                            message(MessageLevel.CriticalWarning, _lines[i].Position, _lines[i].Length, "Unreachable code detected.");
                        }

                        var cn = _lines[i];

                        Parser.Build(
                            ref cn,
                            (codeContext & CodeContext.InEval) != 0 ? 2 : System.Math.Max(1, expressionDepth),
                            variables, codeContext | (_strict ? CodeContext.Strict : CodeContext.None),
                            message,
                            stats,
                            opts | (!unreachable && i == lastRealExp ? Options.SuppressUselessExpressionsElimination | Options.SuppressUselessStatementsElimination : Options.None));

                        if (cn is Empty)
                        {
                            _lines[i] = null;
                        }
                        else
                        {
                            _lines[i] = cn;
                        }

                        unreachable |= cn is Return || cn is Break || cn is Continue || cn is Throw;
                    }
                }
            }

            int f = _lines.Length, t = _lines.Length - 1;

            for (; f-- > 0;)
            {
                if (_lines[f] != null && _lines[t] == null)
                {
                    _lines[t] = _lines[f];
                    _lines[f] = null;
                }

                if (_lines[t] != null)
                {
                    t--;
                }
            }

            if (expressionDepth > 0 && (_variables == null || _variables.Length == 0))
            {
                if (_lines.Length == 0)
                {
                    _this = Empty.Instance;
                }
            }
            else
            {
                if (message != null)
                {
                    for (var i = 0; i < _variables.Length; i++)
                    {
                        if (_variables[i].ReferenceCount == 1 && !(_variables[i].references[0] is ParameterReference))
                        {
                            message(
                                MessageLevel.Recomendation,
                                _variables[i].references[0].Position,
                                0,
                                "Unused variable \"" + _variables[i].name + "\"");
                        }
                        else
                        {
                            break;
                        }
                    }
                }
#if (NET40 || !NETSTANDARD1_3 && !NET40) && JIT
                compiledVersion = JITHelpers.compile(this, depth >= 0);
#endif
            }

            if (t >= 0 && this == _this)
            {
                var newBody = new CodeNode[_lines.Length - t - 1];
                f = 0;
                while (++t < _lines.Length)
                {
                    newBody[f++] = _lines[t];
                }
                _lines = newBody;
            }

            if (_variables != null && _variables.Length != 0)
            {
                for (var i = 0; i < _variables.Length; i++)
                {
                    variables.Remove(_variables[i].name);
                }
            }

            if (variablesToRestore != null)
            {
                for (var i = 0; i < variablesToRestore.Count; i++)
                {
                    variables[variablesToRestore[i].name] = variablesToRestore[i];
                }
            }

            return(false);
        }
コード例 #13
0
ファイル: LabeledStatement.cs プロジェクト: v1rusw0rm/NiL.JS
 public override void Decompose(ref CodeNode self)
 {
     statement.Decompose(ref statement);
 }
コード例 #14
0
 private static JSValue safeGet(JSValue temp, CodeNode source, Context context)
 {
     temp.Assign(source.Evaluate(context));
     return(temp);
 }
コード例 #15
0
        protected override StringBuilder OnConvertToCode(CodeNode currentNode, CodeNode parentNode, CodeRenderService rendererService)
        {
            var    code = new StringBuilder();
            string name = FigmaSharp.Resources.Ids.Conversion.NameIdentifier;

            var frame = (FigmaFrame)currentNode.Node;

            currentNode.Node.TryGetNativeControlType(out FigmaControlType controlType);
            currentNode.Node.TryGetNativeControlVariant(out NativeControlVariant controlVariant);

            if (rendererService.NeedsRenderConstructor(currentNode, parentNode))
            {
                code.WriteConstructor(name, GetControlType(currentNode.Node), rendererService.NodeRendersVar(currentNode, parentNode));
            }

            if (controlType == FigmaControlType.Separator)
            {
                code.WriteEquality(name, nameof(NSBox.BoxType), NSBoxType.NSBoxSeparator);
            }

            if (controlType == FigmaControlType.BoxCustom)
            {
                code.WriteEquality(name, nameof(NSBox.BoxType), NSBoxType.NSBoxCustom);
                bool borderSet = false;

                FigmaVector rectangle = frame.children
                                        .OfType <FigmaVector>()
                                        .FirstOrDefault();

                foreach (var styleMap in rectangle?.styles)
                {
                    if ((rendererService.figmaProvider as NodeProvider).TryGetStyle(styleMap.Value, out FigmaStyle style))
                    {
                        if (styleMap.Key == "fill")
                        {
                            code.WriteEquality(name, nameof(NSBox.FillColor), ColorService.GetNSColorString(style.name));
                        }

                        if (styleMap.Key == "stroke")
                        {
                            code.WriteEquality(name, nameof(NSBox.BorderColor), ColorService.GetNSColorString(style.name));
                            code.WriteEquality(name, nameof(NSBox.BorderWidth), rectangle.strokeWeight.ToString());
                            borderSet = true;
                        }
                    }
                }

                if (!borderSet)
                {
                    code.WriteEquality(name, nameof(NSBox.BorderWidth), "0");
                }
            }

            FigmaText text = frame.children
                             .OfType <FigmaText>()
                             .FirstOrDefault(s => (s.name == ComponentString.TITLE && s.visible));

            if (text != null)
            {
                string stringTitle = CodeHelper.GetTranslatableString(text.characters,
                                                                      rendererService.CurrentRendererOptions.TranslateLabels);

                code.WriteEquality(name, nameof(NSBox.Title), stringTitle,
                                   inQuotes: !rendererService.CurrentRendererOptions.TranslateLabels);
            }
            else
            {
                code.WriteEquality(name, nameof(NSBox.Title), "", inQuotes: true);
            }

            return(code);
        }
コード例 #16
0
        private void ProcessExpression(Expression exp, ParserContext context)
        {
            if (exp == null)
            {
                return;
            }

            if (exp is BinaryExpression)
            {
                var bexp = exp.As <BinaryExpression>();

                ProcessExpression(bexp.Left, context);

                ProcessExpression(bexp.Right, context);
                return;
            }

            if (exp is CallExpression)
            {
                var invexp = exp.As <CallExpression>();
                ProcessExpression(invexp.Callee, context);

                foreach (var arg in invexp.Arguments)
                {
                    var cc = new ParserContext(context, copyNames: true);
                    cc.NameStack.Insert(0, "?");
                    ProcessExpression(arg, cc);
                }
                return;
            }

            if (exp is UnaryExpression)
            {
                var uexp = (UnaryExpression)exp;
                ProcessExpression(uexp.Argument, context);
                return;
            }

            if (exp is IFunctionDeclaration)
            {
                ProcessFunctionDeclaration((IFunctionDeclaration)exp, context);
                return;
            }

            if (exp is ObjectExpression)
            {
                var ojexp = (ObjectExpression)exp;

                if (ojexp.Properties.Any())
                {
                    var codeNode = new CodeNode
                    {
                        Alias       = context.GetNameFromStack(),
                        NodeType    = CodeNodeType.Object,
                        StartLine   = exp.Location.Start.Line,
                        StartColumn = exp.Location.Start.Column,
                        EndLine     = exp.Location.End.Line,
                        EndColumn   = exp.Location.End.Column,
                        Comment     = _comments.GetComment(exp.Location.Start.Line, exp.Location.End.Line)
                    };
                    Hierarchy <CodeNode> hi = context.Nodes.Add(codeNode);

                    foreach (var element in ojexp.Properties)
                    {
                        var childContext = new ParserContext(hi);
                        ProcessExpression((Expression)element.Key, childContext);
                        ProcessExpression(element.Value, childContext);
                    }
                }

                return;
            }

            if (exp is AssignmentExpression)
            {
                var qexp = (AssignmentExpression)exp;
                ProcessExpression(qexp.Left, context);
                ProcessExpression(qexp.Right, context);
                return;
            }

            if (exp is Identifier)
            {
                var iexp = (Identifier)exp;
                context.NameStack.Push(iexp.Name);
                return;
            }

            if (exp is Literal)
            {
                var slexp = (Literal)exp;
                context.NameStack.Push(slexp.Raw);
                return;
            }

            if (exp is MemberExpression)
            {
                var mexp = exp.As <MemberExpression>();
                ProcessExpression(mexp.Property, context);
                ProcessExpression(mexp.Object, new ParserContext(context));
                return;
            }

            if (exp is ArrayExpression)
            {
                var arexp = exp.As <ArrayExpression>();
                foreach (var arelt in arexp.Elements)
                {
                    ProcessExpression(arelt, new ParserContext(context));
                }
            }

            if (exp is NewExpression)
            {
                var nexp = exp.As <NewExpression>();
                foreach (var elt in nexp.Arguments)
                {
                    ProcessExpression(elt, new ParserContext(context.Nodes));
                }
            }

            if (exp is LogicalExpression)
            {
                var lexp = exp.As <LogicalExpression>();
                ProcessExpression(lexp.Left, new ParserContext(context, copyNames: true));
                ProcessExpression(lexp.Right, new ParserContext(context, copyNames: true));
            }

            return;
        }
コード例 #17
0
 protected override StringBuilder OnConvertToCode(CodeNode currentNode, CodeNode parentNode, CodeRenderService rendererService)
 {
     return(new StringBuilder());
 }
コード例 #18
0
 public abstract string ConvertToCode(string propertyName, CodeNode currentNode, CodeNode parentNode, NodeConverter converter, CodeRenderService rendererService);
コード例 #19
0
 static void AssertNoErrors(CodeNode node)
 {
     string error = node.Errors.FirstOrDefault();
     Assert.IsNull(error, error);
 }
コード例 #20
0
 static void AssertUniqueNames(CodeNode node)
 {
     string name = node.Children.GroupBy(c => c.Name).Where(g => g.Count() > 1).FirstOrDefault()?.Key;
     Assert.IsNull(name, $"multiple {name} under {node.Name}");
 }
コード例 #21
0
ファイル: CodeNode.cs プロジェクト: darthwalsh/dotNetBytes
    protected virtual CodeNode ReadField(string fieldName)
    {
        var field     = GetType().GetField(fieldName);
        var fieldType = field.FieldType;

        if (fieldType.IsArray)
        {
            var elementType = fieldType.GetElementType();
            if (elementType.IsValueType)
            {
                int len;
                if (field.TryGetAttribute(out ExpectedAttribute e))
                {
                    if (e.Value is string s)
                    {
                        len = s.Length;
                    }
                    else
                    {
                        len = ((Array)e.Value).Length;
                    }
                }
                else
                {
                    len = GetCount(fieldName);
                }

                var san = typeof(StructArrayNode <>).MakeGenericType(elementType);
                var o   = (CodeNode)Activator.CreateInstance(san, len);
                o.Bytes = Bytes;
                o.Read();

                var value = san.GetField("arr").GetValue(o);
                field.SetValue(this, value);
                o.NodeValue = value.GetString();
                return(o);
            }

            throw new InvalidOperationException($"{GetType().FullName}. {field.Name} is an array {elementType}[]");
        }
        if (fieldType.IsClass)
        {
            var o = (CodeNode)(field.GetValue(this) ?? (CodeNode)Activator.CreateInstance(fieldType));
            o.Bytes = Bytes;
            o.Read();
            field.SetValue(this, o);
            return(o);
        }
        Type sn;

        if (fieldType.IsEnum)
        {
            sn = typeof(EnumNode <>).MakeGenericType(fieldType);;
        }
        else if (fieldType.IsValueType)
        {
            sn = typeof(StructNode <>).MakeGenericType(fieldType);
        }
        else
        {
            throw new InvalidOperationException(fieldType.Name);
        }
        {
            CodeNode o = (CodeNode)Activator.CreateInstance(sn);
            o.Bytes = Bytes;
            o.Read();
            var value = sn.GetField("t").GetValue(o);
            field.SetValue(this, value);
            o.NodeValue = value.GetString();
            return(o);
        }
    }
コード例 #22
0
    public CodeNode Read(Stream stream)
    {
        CodeNode rva;

        Node = new CodeNode
        {
            (rva = stream.ReadStruct(out RVA, nameof(RVA))),
            stream.ReadClass(ref ImplFlags, nameof(ImplFlags)),
            stream.ReadClass(ref Flags, nameof(Flags)),
            stream.ReadClass(ref Name, nameof(Name)),
            stream.ReadClass(ref Signature, nameof(Signature)),
            stream.ReadClass(ref ParamList, nameof(ParamList)),
        };

        rva.DelayedValueNode = () => new DefaultValueNode(
            rva.Value,
            RVA > 0 ? Singletons.Instance.MethodsByRVA[RVA].Node : null);

        return Node;
    }
コード例 #23
0
 public override string ConvertToCode(string propertyName, CodeNode currentNode, CodeNode parentNode, CodeRenderService rendererService)
 {
     if (currentNode.Node.Parent != null && propertyName == PropertyNames.AddChild)
     {
         var defaultParentName = GetDefaultParentName(currentNode, parentNode, rendererService);
         if (!string.IsNullOrEmpty(defaultParentName))
         {
             return(CodeGenerationHelpers.GetMethod(defaultParentName, nameof(NSView.AddSubview), currentNode.Name));
         }
     }
     return(base.ConvertToCode(propertyName, currentNode, parentNode, rendererService));
 }
コード例 #24
0
 public override string ConvertToCode(CodeNode currentNode, CodeNode parentNode, CodeRenderService rendererService)
 {
     return(string.Empty);
 }
コード例 #25
0
ファイル: ScopeNode.cs プロジェクト: Crondale/SassSharp
 public virtual void Add(CodeNode node)
 {
     node.Parent = this;
     _nodes.Add(node);
 }
コード例 #26
0
ファイル: With.cs プロジェクト: viceice/NiL.JS
        internal static CodeNode Parse(ParseInfo state, ref int index)
        {
            int i = index;

            if (!Parser.Validate(state.Code, "with (", ref i) && !Parser.Validate(state.Code, "with(", ref i))
            {
                return(null);
            }
            if (state.Strict)
            {
                ExceptionHelper.Throw((new NiL.JS.BaseLibrary.SyntaxError("WithStatement is not allowed in strict mode.")));
            }

            if (state.Message != null)
            {
                state.Message(MessageLevel.CriticalWarning, index, 4, "Do not use \"with\".");
            }

            var obj = Parser.Parse(state, ref i, CodeFragmentType.Expression);

            while (Tools.IsWhiteSpace(state.Code[i]))
            {
                i++;
            }
            if (state.Code[i] != ')')
            {
                ExceptionHelper.Throw((new NiL.JS.BaseLibrary.SyntaxError("Invalid syntax WithStatement.")));
            }
            do
            {
                i++;
            }while (Tools.IsWhiteSpace(state.Code[i]));

            CodeNode body = null;

            VariableDescriptor[] vars = null;
            var oldVariablesCount     = state.Variables.Count;

            state.LexicalScopeLevel++;
            using (state.WithCodeContext(CodeContext.InWith))
            {
                try
                {
                    body = Parser.Parse(state, ref i, 0);
                    vars = CodeBlock.extractVariables(state, oldVariablesCount);
                    body = new CodeBlock(new[] { body })
                    {
                        _variables = vars,
                        Position   = body.Position,
                        Length     = body.Length
                    };
                }
                finally
                {
                    state.LexicalScopeLevel--;
                }
            }

            var pos = index;

            index = i;
            return(new With()
            {
                _scope = obj,
                _body = body,
                Position = pos,
                Length = index - pos
            });
        }
コード例 #27
0
 public override void Optimize(ref CodeNode _this, FunctionDefinition owner, CompilerMessageCallback message, Options opts, FunctionInfo stats)
 {
     base.Optimize(ref _this, owner, message, opts, stats);
 }
コード例 #28
0
ファイル: TryCatch.cs プロジェクト: v1rusw0rm/NiL.JS
        public override bool Build(ref CodeNode _this, int expressionDepth, Dictionary <string, VariableDescriptor> variables, CodeContext codeContext, InternalCompilerMessageCallback message, FunctionInfo stats, Options opts)
        {
            if (stats != null)
            {
                stats.ContainsTry = true;
            }

            Parser.Build(ref body, expressionDepth, variables, codeContext | CodeContext.Conditional, message, stats, opts);
            var catchPosition = Position;

            if (catchBody != null)
            {
                _catch = true;
                catchVariableDesc.owner = this;
                VariableDescriptor oldVarDesc = null;
                variables.TryGetValue(catchVariableDesc.name, out oldVarDesc);
                variables[catchVariableDesc.name] = catchVariableDesc;
                catchPosition = catchBody.Position;
                Parser.Build(ref catchBody, expressionDepth, variables, codeContext | CodeContext.Conditional, message, stats, opts);
                if (oldVarDesc != null)
                {
                    variables[catchVariableDesc.name] = oldVarDesc;
                }
                else
                {
                    variables.Remove(catchVariableDesc.name);
                }
            }

            var finallyPosition = 0;

            if (finallyBody != null)
            {
                finallyPosition = finallyBody.Position;
                Parser.Build(ref finallyBody, expressionDepth, variables, codeContext, message, stats, opts);
            }

            if (body == null || (body is Empty))
            {
                if (message != null)
                {
                    message(MessageLevel.Warning, Position, Length, "Empty (or reduced to empty) try" + (catchBody != null ? "..catch" : "") + (finallyBody != null ? "..finally" : "") + " block. Maybe, something missing.");
                }

                _this = finallyBody;
            }

            if (_catch && (catchBody == null || (catchBody is Empty)))
            {
                if (message != null)
                {
                    message(MessageLevel.Warning, catchPosition, (catchBody ?? this as CodeNode).Length, "Empty (or reduced to empty) catch block. Do not ignore exceptions.");
                }
            }

            if (finallyPosition != 0 && (finallyBody == null || (finallyBody is Empty)))
            {
                if (message != null)
                {
                    message(MessageLevel.Warning, catchPosition, (catchBody ?? this as CodeNode).Length, "Empty (or reduced to empty) finally block.");
                }
            }

            return(false);
        }
コード例 #29
0
        protected override StringBuilder OnConvertToCode(CodeNode currentNode, CodeNode parentNode, ICodeRenderService rendererService)
        {
            var code = new StringBuilder();

            // TODO: Get name from generator
            var    name            = currentNode.Name + "ScrollView";
            string outlineViewName = currentNode.Name;

            currentNode.Name = name;
            var frame = (FigmaFrame)currentNode.Node;

            code.WriteConstructor(name, typeof(NSScrollView));
            code.WritePropertyEquality(name, nameof(NSScrollView.AutoresizingMask),
                                       $"{nameof(NSViewResizingMask)}.{nameof(NSViewResizingMask.WidthSizable)} | " +
                                       $"{nameof(NSViewResizingMask)}.{nameof(NSViewResizingMask.HeightSizable)}");

            code.WritePropertyEquality(name, nameof(NSScrollView.BorderType), NSBorderType.BezelBorder);
            code.WritePropertyEquality(name, nameof(NSScrollView.DrawsBackground), true);
            code.AppendLine();

            if (rendererService.NeedsRenderConstructor(currentNode, parentNode))
            {
                code.WriteConstructor(outlineViewName, typeof(NSOutlineView), rendererService.NodeRendersVar(currentNode, parentNode));
            }

            code.WritePropertyEquality(outlineViewName, nameof(NSOutlineView.Frame),
                                       string.Format("new {0} ({1}, {2}, {3}, {4})",
                                                     typeof(CoreGraphics.CGRect), 0, 0, name + ".ContentSize.Width", name + ".ContentSize.Height"));

            var columnNodes = frame.FirstChild(s => s.name == ComponentString.COLUMNS && s.visible);

            // TODO: Parse options layers
            code.WritePropertyEquality(outlineViewName, nameof(NSOutlineView.UsesAlternatingRowBackgroundColors), false);
            code.WritePropertyEquality(outlineViewName, nameof(NSOutlineView.AllowsMultipleSelection), false);
            code.WritePropertyEquality(outlineViewName, nameof(NSOutlineView.AllowsColumnResizing), true);
            code.WritePropertyEquality(outlineViewName, nameof(NSOutlineView.AllowsColumnReordering), false);
            code.WritePropertyEquality(outlineViewName, nameof(NSOutlineView.AllowsEmptySelection), false);
            code.AppendLine();

            int columnCount = 1;

            foreach (FigmaNode tableColumNode in columnNodes.GetChildren(t => t.visible))
            {
                FigmaText text = tableColumNode.FirstChild(s => s.name == ComponentString.TITLE) as FigmaText;

                if (text == null)
                {
                    continue;
                }

                string columnId = "OutlineColumn" + columnCount;

                code.WriteConstructor(columnId, typeof(NSTableColumn));

                code.WritePropertyEquality(columnId,
                                           $"{nameof(NSTableColumn.HeaderCell)}.{nameof(NSTableColumn.HeaderCell.Alignment)}",
                                           Helpers.CodeHelper.GetNSTextAlignmentString(text));

                code.WritePropertyEquality(columnId, nameof(NSTableColumn.Identifier), columnId, inQuotes: true);
                code.WritePropertyEquality(columnId, nameof(NSTableColumn.Title), rendererService.GetTranslatedText(text), inQuotes: true);
                code.WritePropertyEquality(columnId, nameof(NSTableColumn.Width), text.absoluteBoundingBox.Width.ToString(), inQuotes: false);
                code.WriteMethod(outlineViewName, nameof(NSOutlineView.AddColumn), columnId);
                code.AppendLine();

                if (columnCount == 1)
                {
                    code.WritePropertyEquality(outlineViewName, nameof(NSOutlineView.OutlineTableColumn), columnId);
                }

                columnCount++;
            }

            code.WritePropertyEquality(name, nameof(NSScrollView.DocumentView), outlineViewName, inQuotes: false);
            code.AppendLine();


            var rectangle = (RectangleVector)frame.FirstChild(s => s.name == ComponentString.BACKGROUND && s.visible);

            if (rectangle != null)
            {
                foreach (var styleMap in rectangle.styles)
                {
                    if (rendererService.NodeProvider.TryGetStyle(styleMap.Value, out FigmaStyle style) &&
                        styleMap.Key == "fill")
                    {
                        code.WritePropertyEquality(outlineViewName, nameof(NSOutlineView.BackgroundColor), ColorService.GetNSColorString(style.name));
                    }
                }
            }


            return(code);
        }
コード例 #30
0
        public override void Optimize(ref CodeNode _this, FunctionDefinition owner, InternalCompilerMessageCallback message, Options opts, FunctionInfo stats)
        {
            baseOptimize(ref _this, owner, message, opts, stats);
            var vr = _left as VariableReference;

            if (vr != null)
            {
                if (vr._descriptor.IsDefined)
                {
                    var stype = _right.ResultType;
                    if (vr._descriptor.lastPredictedType == PredictedType.Unknown)
                    {
                        vr._descriptor.lastPredictedType = stype;
                    }
                    else if (vr._descriptor.lastPredictedType != stype)
                    {
                        if (Tools.IsEqual(vr._descriptor.lastPredictedType, stype, PredictedType.Group))
                        {
                            vr._descriptor.lastPredictedType = stype & PredictedType.Group;
                        }
                        else
                        {
                            if (message != null && stype >= PredictedType.Undefined && vr._descriptor.lastPredictedType >= PredictedType.Undefined)
                            {
                                message(MessageLevel.Warning, Position, Length, "Variable \"" + vr.Name + "\" has ambiguous type. It can be make impossible some optimizations and cause errors.");
                            }
                            vr._descriptor.lastPredictedType = PredictedType.Ambiguous;
                        }
                    }
                }
                else if (message != null)
                {
                    message(MessageLevel.CriticalWarning, Position, Length, "Assign to undefined variable \"" + vr.Name + "\". It will declare a global variable.");
                }
            }

            var variable = _left as Variable;

            if (variable != null && variable._descriptor.IsDefined && (_codeContext & CodeContext.InWith) == 0 && !variable._descriptor.captured)
            {
                if (!stats.ContainsEval && !stats.ContainsWith)
                {
                    if (owner != null // не будем это применять в корневом узле. Только в функциях.
                                      // Иначе это может использоваться как настройка контекста для последующего использования в Eval
                        && (opts & Options.SuppressUselessExpressionsElimination) == 0 &&
                        (_codeContext & CodeContext.InLoop) == 0)
                    {
                        if ((owner._body._strict || variable._descriptor.owner != owner || !owner._functionInfo.ContainsArguments)) // аргументы это одна сущность с двумя именами
                        {
                            bool last = true;
                            for (var i = 0; last && i < variable._descriptor.references.Count; i++)
                            {
                                last &= variable._descriptor.references[i].Eliminated || variable._descriptor.references[i].Position <= Position;
                            }

                            if (last)
                            {
                                if (_right.ContextIndependent)
                                {
                                    _this.Eliminated = true;
                                    _this            = Empty.Instance;
                                }
                                else
                                {
                                    _this           = _right;
                                    this._right     = null;
                                    this.Eliminated = true;
                                    this._right     = _this as Expression;
                                }
                            }
                        }
                    }
                }

                /*if (_this == this && second.ResultInTempContainer) // это присваивание, не последнее, без with
                 * {
                 *  _this = new AssignmentOverReplace(first, second)
                 *  {
                 *      Position = Position,
                 *      Length = Length,
                 *      _codeContext = _codeContext
                 *  };
                 * }*/
            }
        }
コード例 #31
0
 public override string ConvertToCode(CodeNode currentNode, CodeNode parentNode, ICodeRenderService rendererService) => string.Empty;
コード例 #32
0
 static void AssertChildrenDontOverlap(CodeNode node)
 {
     foreach (var o in node.Children.Zip(node.Children.Skip(1), (last, next) => new { last, next }))
     {
         Asserts.IsLessThanOrEqual(o.last.End, o.next.Start);
     }
 }
コード例 #33
0
        void Recommendations(StructuredReport report)
        {
            CodeNode findings = new CodeNode(new CodedEntry("111017", "DCM", "CAD Processing and Findings Summary"));

            report.Root.Add(findings, RelationshipType.Contains);
        }
コード例 #34
0
 static void AssertLinkOrChildren(CodeNode node)
 {
     if (node.LinkPath != null && node.Children.Any())
     {
         Assert.Fail(node.Name);
     }
 }
コード例 #35
0
        public override CodeNode Construct(AASTNode aastNode, CodeNode?parent)
        {
            // prim [ iden, call args ]
            //
            // Generate call bytes.
            // TODO: Dot notation (routines in modules)
            //
            // Construct parameters and put them in the stack
            // Deallocate everything
            // R27 = SB + offset(func);
            // if R27 goto R27;
            // Allocate back
            // Manage return value (if any)

            Generator g   = Program.currentCompiler.generator;
            Context?  ctx = SemanticAnalyzer.FindParentContext(aastNode)
                            ?? throw new CompilationErrorException("No parent context found!!!\r\n  At line " + aastNode.Token.Position.Line);
            CodeNode callNode = new CodeNode(aastNode, parent);

            int            i          = 0;
            List <VarType> paramTypes = ((RoutineType)ctx.GetVarType(aastNode.Children[0].Token)).ParamTypes;
            int            param_i    = 8;

            foreach (AASTNode expr in aastNode.Children[1].Children)
            {
                CodeNode exprNode = base.Construct(expr, callNode);
                byte     fr0      = exprNode.ByteToReturn;
                callNode.Children.AddLast(exprNode);

                CodeNode fr1Node = GetFreeRegisterNode(ctx, callNode);
                byte     fr1     = fr1Node.ByteToReturn;
                callNode.Children.AddLast(fr1Node);

                CodeNode fr2Node = GetFreeRegisterNode(ctx, callNode);
                byte     fr2     = fr2Node.ByteToReturn;
                callNode.Children.AddLast(fr2Node);

                // Store parameters depending on their size on the stack before we enter a routine.
                int mask  = paramTypes[i].GetSize() == 4 ? 0 : ((int)Math.Pow(256, 4) - 1) << (8 * paramTypes[i].GetSize()); // ff ff ff 00 or ff ff 00 00 or 00 00 00 00
                int mask2 = paramTypes[i].GetSize() == 4 ? -1 : (int)Math.Pow(256, paramTypes[i].GetSize()) - 1;             // 00 00 00 ff or 00 00 ff ff or ff ff ff ff

                callNode.Children.AddLast(new CodeNode("Parameter store", callNode)
                                          .Add(GenerateMOV(SP, 27))
                                          .Add(GenerateLDA(27, 27, param_i - 4 + paramTypes[i].GetSize()))
                                          .Add(GenerateLD(27, fr1))
                                          .Add(GenerateLDC(0, fr2))
                                          .Add(GenerateLDA(fr2, fr2, mask))
                                          .Add(GenerateAND(fr2, fr1))
                                          .Add(GenerateLDC(0, fr2))
                                          .Add(GenerateLDA(fr2, fr2, mask2))
                                          .Add(GenerateAND(fr2, fr0))
                                          .Add(GenerateOR(fr1, fr0))
                                          .Add(GenerateST(fr0, 27)));

                param_i += paramTypes[i].GetSize();
                i++;
                g.FreeReg(fr0);
                g.FreeReg(fr1);
                g.FreeReg(fr2);
            }

            // Recursively deallocate (statement-unaware) evertything, basically, up the AAST tree since we change our context completely.
            AASTNode mainContextNode = aastNode;

            while (!mainContextNode.ASTType.Equals("Program") && !mainContextNode.ASTType.Equals("Module"))
            {
                if (mainContextNode.Parent == null)
                {
                    throw new CompilationErrorException("Routine call is bad!!! (how did you manage to do that!?)");
                }
                if (mainContextNode.Context != null)
                {
                    callNode.Children.AddLast(GetRegisterDeallocationNode(mainContextNode, callNode, false));
                }
                mainContextNode = (AASTNode)mainContextNode.Parent;
            }
            callNode.Children.AddLast(new CodeNode("Call jump", callNode)
                                      .Add(GenerateLDA(SB, 27, ctx.GetStaticOffset(aastNode.Children[0].Token.Value))) // TODO: module routine jumps. Here are only pure static routines.
                                      .Add(GenerateLD(27, 27))
                                      .Add(GenerateCBR(27, 27)));

            // If routine is not NO_TYPE, then it has returned something and this return value is always in R26.
            if (ctx.GetRoutineReturnType(aastNode.Children[0].Token).Type != VarType.ERAType.NO_TYPE) // Return value is in R26
            {
                CodeNode fr0Node = GetFreeRegisterNode(aastNode, callNode);
                byte     fr0     = fr0Node.ByteToReturn;
                callNode.Children.AddLast(fr0Node);
                callNode.Children.AddLast(new CodeNode("return value", callNode).Add(GenerateMOV(26, fr0)));
                callNode.ByteToReturn = fr0;
                g.FreeReg(26);
            }

            return(callNode);
        }
コード例 #36
0
 static void AssertParentDifferentSizeThanChild(CodeNode node)
 {
     if (node.Children.Count == 1 && node.Start == node.Children.Single().Start && node.End == node.Children.Single().End)
     {
         if (exceptions.Any(sub => node.Name.Contains(sub)))
         {
             return;
         }
         Assert.Fail(string.Join("\r\n", node));
     }
 }
コード例 #37
0
 public override bool Build(ref CodeNode _this, int expressionDepth, Dictionary <string, VariableDescriptor> variables, CodeContext codeContext, InternalCompilerMessageCallback message, FunctionInfo stats, Options opts)
 {
     stats.NeedDecompose = true;
     return(base.Build(ref _this, expressionDepth, variables, codeContext, message, stats, opts));
 }
コード例 #38
0
 internal override bool Build(ref CodeNode _this, int depth, System.Collections.Generic.Dictionary<string, VariableDescriptor> variables, _BuildState state, CompilerMessageCallback message, FunctionStatistics statistic, Options opts)
 {
     return false;
 }
コード例 #39
0
 /// <summary>
 /// Add condition argument to given node.
 /// </summary>
 /// <param name="condNode">Node to add condition argument.</param>
 private void condition(CodeNode condNode)
 {
     _shiftToken("(", "expected '{0}' in {1} clause", condNode.Value);
     condNode.AddArgument(_nextTree());
     _shiftToken(")", "expected '{0}' in {1} clause", condNode.Value);
 }
コード例 #40
0
    public CodeNode Read(Stream stream)
    {
        Node = new CodeNode
        {
            stream.ReadStruct(out Offset, nameof(Offset)),
            stream.ReadStruct(out Flags, nameof(Flags)),
            stream.ReadClass(ref Name, nameof(Name)),
            stream.ReadClass(ref Implementation, nameof(Implementation)),
        };

        Section section = Singletons.Instance.TildeStream.Section;
        section.ReadNode(strm =>
        {
            section.Reposition(strm, section.CLIHeader.Resources.RVA + Offset);

            ResourceEntry entry = null;
            return stream.ReadClass(ref entry);
        });

        return Node;
    }
コード例 #41
0
ファイル: This.cs プロジェクト: viceice/NiL.JS
 public override bool Build(ref CodeNode _this, int expressionDepth, Dictionary <string, VariableDescriptor> variables, CodeContext codeContext, InternalCompilerMessageCallback message, FunctionInfo stats, Options opts)
 {
     return(false);
 }
コード例 #42
0
ファイル: NavigationTreeView.cs プロジェクト: hxhlb/jsparser
 private bool FindCallBack(CodeNode codeNode)
 {
     try
     {
         var node = SearchNode(treeView1.Nodes, codeNode);
         if (node != null)
         {
             treeView1.SelectedNode = node;
             GotoSelected();
         }
         else
         {
             _codeProvider.SelectionMoveToLineAndOffset(codeNode.StartLine, codeNode.StartColumn + 1);
             _codeProvider.SetFocus();
         }
     }
     catch { }
     return true;
 }
コード例 #43
0
        internal override bool Build(ref CodeNode _this, int depth, Dictionary<string, VariableDescriptor> variables, _BuildState state, CompilerMessageCallback message, FunctionStatistics statistic, Options opts)
        {
            depth = System.Math.Max(1, depth);
            Parser.Build(ref body, depth, variables, state | _BuildState.InLoop, message, statistic, opts);
            Parser.Build(ref condition, 2, variables, state | _BuildState.InLoop, message, statistic, opts);
            try
            {
                if (allowRemove
                    && (opts & Options.SuppressUselessExpressionsElimination) == 0
                    && (condition is Constant || (condition as Expressions.Expression).IsContextIndependent))
                {
                    if ((bool)condition.Evaluate(null))
                        _this = new InfinityLoop(body, labels);
                    else if (labels.Length == 0)
                        _this = body;
                    condition.Eliminated = true;
                }
            }

#if PORTABLE
            catch
            {
コード例 #44
0
 public override string ConvertToCode(CodeNode currentNode, CodeNode parent, CodeRenderService rendererService)
 {
     return($"var [NAME] = new {typeof(Xamarin.Forms.Button).FullName}();");
 }
コード例 #45
0
 public override void Decompose(ref CodeNode self)
 {
     throw new InvalidOperationException();
 }
コード例 #46
0
        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));
        }
コード例 #47
0
        internal static CodeNode Parse(ParseInfo state, ref int index)
        {
            //string code = state.Code;
            int i = index;

            if (!Parser.Validate(state.Code, "while (", ref i) && !Parser.Validate(state.Code, "while(", ref i))
            {
                return(null);
            }
            int labelsCount = state.LabelsCount;

            state.LabelsCount = 0;
            while (Tools.IsWhiteSpace(state.Code[i]))
            {
                i++;
            }
            var condition = Parser.Parse(state, ref i, CodeFragmentType.Expression);

            while (i < state.Code.Length && Tools.IsWhiteSpace(state.Code[i]))
            {
                i++;
            }
            if (i >= state.Code.Length)
            {
                ExceptionHelper.Throw(new SyntaxError(Strings.UnexpectedEndOfSource));
            }
            if (state.Code[i] != ')')
            {
                throw new ArgumentException("code (" + i + ")");
            }
            do
            {
                i++;
            }while (i < state.Code.Length && Tools.IsWhiteSpace(state.Code[i]));
            if (i >= state.Code.Length)
            {
                ExceptionHelper.ThrowSyntaxError(Strings.UnexpectedEndOfSource);
            }
            state.AllowBreak.Push(true);
            state.AllowContinue.Push(true);
            int ccs  = state.ContiniesCount;
            int cbs  = state.BreaksCount;
            var body = Parser.Parse(state, ref i, 0);

            if (body is FunctionDefinition)
            {
                if (state.Message != null)
                {
                    state.Message(MessageLevel.CriticalWarning, body.Position, body.Length, Strings.DoNotDeclareFunctionInNestedBlocks);
                }
                body = new CodeBlock(new[] { body }); // для того, чтобы не дублировать код по декларации функции,
                // она оборачивается в блок, который сделает самовыпил на втором этапе, но перед этим корректно объявит функцию.
            }
            state.AllowBreak.Pop();
            state.AllowContinue.Pop();
            var pos = index;

            index = i;
            return(new While()
            {
                allowRemove = ccs == state.ContiniesCount && cbs == state.BreaksCount,
                body = body,
                condition = condition,
                labels = state.Labels.GetRange(state.Labels.Count - labelsCount, labelsCount).ToArray(),
                Position = pos,
                Length = index - pos
            });
        }
コード例 #48
0
 public override void Decompose(ref CodeNode self)
 {
     _variable.Decompose(ref _variable);
     _source.Decompose(ref _source);
     _body?.Decompose(ref _body);
 }
コード例 #49
0
ファイル: While.cs プロジェクト: Oceanswave/NiL.JS
        internal static CodeNode Parse(ParseInfo state, ref int index)
        {
            //string code = state.Code;
            int i = index;

            if (!Parser.Validate(state.Code, "while (", ref i) && !Parser.Validate(state.Code, "while(", ref i))
            {
                return(null);
            }
            int labelsCount = state.LabelsCount;

            state.LabelsCount = 0;
            while (Tools.IsWhiteSpace(state.Code[i]))
            {
                i++;
            }
            var condition = Parser.Parse(state, ref i, CodeFragmentType.Expression);

            while (i < state.Code.Length && Tools.IsWhiteSpace(state.Code[i]))
            {
                i++;
            }
            if (i >= state.Code.Length)
            {
                ExceptionHelper.Throw(new SyntaxError("Unexpected end of line."));
            }
            if (state.Code[i] != ')')
            {
                throw new ArgumentException("code (" + i + ")");
            }
            do
            {
                i++;
            }while (i < state.Code.Length && Tools.IsWhiteSpace(state.Code[i]));
            if (i >= state.Code.Length)
            {
                ExceptionHelper.Throw(new SyntaxError("Unexpected end of line."));
            }
            state.AllowBreak.Push(true);
            state.AllowContinue.Push(true);
            int ccs  = state.continiesCount;
            int cbs  = state.breaksCount;
            var body = Parser.Parse(state, ref i, 0);

            if (body is FunctionDefinition)
            {
                if (state.strict)
                {
                    ExceptionHelper.Throw((new NiL.JS.BaseLibrary.SyntaxError("In strict mode code, functions can only be declared at top level or immediately within another function.")));
                }
                if (state.message != null)
                {
                    state.message(MessageLevel.CriticalWarning, CodeCoordinates.FromTextPosition(state.Code, body.Position, body.Length), "Do not declare function in nested blocks.");
                }
                body = new CodeBlock(new[] { body }); // для того, чтобы не дублировать код по декларации функции,
                // она оборачивается в блок, который сделает самовыпил на втором этапе, но перед этим корректно объявит функцию.
            }
            state.AllowBreak.Pop();
            state.AllowContinue.Pop();
            var pos = index;

            index = i;
            return(new While()
            {
                allowRemove = ccs == state.continiesCount && cbs == state.breaksCount,
                body = body,
                condition = condition,
                labels = state.Labels.GetRange(state.Labels.Count - labelsCount, labelsCount).ToArray(),
                Position = pos,
                Length = index - pos
            });
        }
コード例 #50
0
ファイル: WhileStatement.cs プロジェクト: modulexcite/NiL.JS
        internal override bool Build(ref CodeNode _this, int depth, Dictionary<string, VariableDescriptor> variables, _BuildState state, CompilerMessageCallback message, FunctionStatistics statistic, Options opts)
        {
            depth = System.Math.Max(1, depth);
            Parser.Build(ref body, depth, variables, state | _BuildState.Conditional | _BuildState.InLoop, message, statistic, opts);
            Parser.Build(ref condition, 2, variables, state | _BuildState.InLoop, message, statistic, opts);
            if ((opts & Options.SuppressUselessExpressionsElimination) == 0 && condition is ToBool)
            {
                if (message == null)
                    message(MessageLevel.Warning, new CodeCoordinates(0, condition.Position, 2), "Useless conversion. Remove double negation in condition");
                condition = (condition as Expression).first;
            }
            try
            {
                if (allowRemove && (condition is Constant || (condition is Expression && (condition as Expression).IsContextIndependent)))
                {
                    if ((bool)condition.Evaluate(null))
                    {
                        if ((opts & Options.SuppressUselessExpressionsElimination) == 0)
                            _this = new InfinityLoop(body, labels);
                    }
                    else if ((opts & Options.SuppressUselessStatementsElimination) == 0)
                    {
                        _this = null;
                        Eliminated = true;
                        body.Eliminated = true;
                    }
                    condition.Eliminated = true;
                }
                else if ((opts & Options.SuppressUselessExpressionsElimination) == 0
                        && ((condition is Json && (condition as Json).Fields.Length == 0)
                            || (condition is ArrayExpression && (condition as ArrayExpression).Elements.Count == 0)))
                {
                    _this = new InfinityLoop(body, labels);
                    condition.Eliminated = true;
                }
            }
#if PORTABLE
            catch
            {
コード例 #51
0
        public virtual void ColorLineForDisplay(int lineIndex, int[] colors)
        {
            if (this.EditingObserverExtension.AnalyzingResult == null || this.EditingObserverExtension.AnalyzingResult.Unit == null)
            {
                return;
            }
            TextLine <TextEditorBox.LineInfo> line = this.Callback.TextEditorBox.TextProvider[lineIndex];

            foreach (var token in this.EditingObserverExtension.AnalyzingResult.IdTokens[lineIndex])
            {
                bool         needColor = false;
                TextPosition tokenPos  = new TextPosition(token.Start.row, (token.Start.col + token.End.col) / 2);
                {
                    var type = this.EditingObserverExtension.AnalyzingResult.Unit.FindDeepest <NativeXReferenceType>(tokenPos);
                    if (type != null && type.ReferencedName == token.Value)
                    {
                        CodeScope scope = type.Scope;
                        if (scope != null)
                        {
                            CodeNode node = type.Scope.Find(type.ReferencedName);
                            if (node is NativeXTypeRenameDeclaration || node is NativeXStructureDeclaration)
                            {
                                needColor = true;
                            }
                        }
                    }
                }
                {
                    var conref = this.EditingObserverExtension.AnalyzingResult.Unit.FindDeepest <NativeXConceptReference>(tokenPos);
                    if (conref != null && conref.ReferenceName == token.Value)
                    {
                        CodeScope scope = conref.Scope;
                        if (scope != null)
                        {
                            CodeNode node = conref.Scope.Find(conref.ReferenceName);
                            if (node is NativeXConceptDeclaration)
                            {
                                needColor = true;
                            }
                        }
                    }
                }
                {
                    var decl = this.EditingObserverExtension.AnalyzingResult.Unit.FindDeepest <NativeXNode>(tokenPos) as NativeXDeclaration;
                    if (decl != null && decl.Name == token.Value)
                    {
                        if (decl is NativeXStructureDeclaration || decl is NativeXTypeRenameDeclaration || decl is NativeXConceptDeclaration)
                        {
                            needColor = true;
                        }
                    }
                }
                if (needColor)
                {
                    int start = Math.Max(0, Math.Min(token.Start.col, line.CharCount - 1));
                    int end   = Math.Min(token.End.col, line.CharCount);
                    for (int i = start; i < end; i++)
                    {
                        colors[i] = NativeXColorizer.TypeColorId;
                    }
                }
            }
        }