Example #1
0
        /// <summary>
        /// Load program from ascii, bytecode or protected stream.
        /// </summary>
        /// <param name="stream">Program stream</param>
        /// <param name="rebuildLineNumber">Should rebuild line numbers</param>
        public void Load(Stream stream, bool rebuildLineNumber = true)
        {
            Erase();
            var programMode = FindDocumentType(stream);

            Bytecode.WriteByte((byte)programMode);
            switch (programMode)
            {
            case ProgramMode.Binary:
                stream.CopyTo(Bytecode);
                break;

            case ProgramMode.Protected:
                _protected = AllowProtect;
                ProtectedProgramEncoder.Decode(stream).CopyTo(Bytecode);
                break;

            case ProgramMode.Ascii:
                Merge(stream);
                break;
            }

            if (rebuildLineNumber && programMode != ProgramMode.Ascii)
            {
                RebuildLineNumbers();
            }
        }
Example #2
0
 public virtual void Emit1(CommonTree opAST, Bytecode opcode, int arg)
 {
     Emit(opAST, opcode);
     EnsureCapacity(Instruction.OperandSizeInBytes);
     WriteShort(impl.instrs, ip, (short)arg);
     ip += Instruction.OperandSizeInBytes;
 }
Example #3
0
 public ILTranslator(Bytecode bytecode)
 {
     builder = new AntlrRunnableBuilder();
     builder.Load(bytecode.Script);
     runnable = builder.Build();
     name = bytecode.FunctionNames[0];
 }
Example #4
0
        public virtual void Insert(int addr, Bytecode opcode, string s)
        {
            //System.out.println("before insert of "+opcode+"("+s+"):"+ Arrays.toString(impl.instrs));
            EnsureCapacity(1 + Instruction.OperandSizeInBytes);
            int instrSize = 1 + Instruction.OperandSizeInBytes;

            // make room for opcode, opnd
            Array.Copy(impl.instrs, addr, impl.instrs, addr + instrSize, ip - addr);
            int save = ip;

            ip = addr;
            Emit1(null, opcode, s);
            ip = save + instrSize;
            //System.out.println("after  insert of "+opcode+"("+s+"):"+ Arrays.toString(impl.instrs));
            // adjust addresses for BR and BRF
            int a = addr + instrSize;

            while (a < ip)
            {
                Bytecode    op = (Bytecode)impl.instrs[a];
                Instruction I  = Instruction.instructions[(int)op];
                if (op == Bytecode.INSTR_BR || op == Bytecode.INSTR_BRF)
                {
                    int opnd = BytecodeDisassembler.GetShort(impl.instrs, a + 1);
                    WriteShort(impl.instrs, a + 1, (short)(opnd + instrSize));
                }
                a += I.nopnds * Instruction.OperandSizeInBytes + 1;
            }
            //System.out.println("after  insert of "+opcode+"("+s+"):"+ Arrays.toString(impl.instrs));
        }
Example #5
0
        /// <summary>
        ///     Submits <see cref="Bytecode" /> for evaluation to a remote Gremlin Server.
        /// </summary>
        /// <param name="bytecode">The <see cref="Bytecode" /> to submit.</param>
        /// <returns>A <see cref="ITraversal" /> allowing to access the results and side-effects.</returns>
        public async Task <ITraversal <S, E> > SubmitAsync <S, E>(Bytecode bytecode)
        {
            var requestId = Guid.NewGuid();
            var resultSet = await SubmitBytecodeAsync(requestId, bytecode).ConfigureAwait(false);

            return(new DriverRemoteTraversal <S, E>(_client, requestId, resultSet));
        }
Example #6
0
        /// <summary>
        /// Serializes the specified bytecode.
        /// </summary>
        /// <param name="bytecode">The bytecode.</param>
        private void Serialize(Bytecode bytecode)
        {
            var first = true;

            foreach (var instr in bytecode.SourceInstructions)
            {
                if (!first)
                {
                    _writer.Write('.');
                }

                _writer.Write(instr.OperatorName);

                first = false;
            }

            foreach (var instr in bytecode.StepInstructions)
            {
                if (!first)
                {
                    _writer.Write('.');
                }

                Serialize(instr);

                first = false;
            }
        }
        private DefaultTraversal <object, object> CreateTraversalWithRemoteStrategy(Bytecode bytecode)
        {
            var remoteStrategy =
                new RemoteStrategy(new DriverRemoteConnection(new GremlinClient(new GremlinServer(TestHost, TestPort))));

            return(new TestTraversal(remoteStrategy, bytecode));
        }
Example #8
0
        /// <summary>
        /// Update line number dictionary after deleting lines.
        /// </summary>
        private void UpdateLineMap(CodePosition position, int length)
        {
            // subtract length of line we replaced
            length -= (int)(position.AfterPosition - position.StartPosition);
            var address = Position + 1 + position.AfterPosition;

            Bytecode.Seek(position.AfterPosition + length + 1, SeekOrigin.Begin); // pass \x00
            while (true)
            {
                var nextAddressStr = Bytecode.Read(2);
                if (nextAddressStr.Length < 2 || nextAddressStr == "\0\0")
                {
                    break;
                }

                var nextAddress = nextAddressStr.ToUnsignedInteger();
                Bytecode.Seek(-2, SeekOrigin.Current);
                Bytecode.Write((nextAddress + length).ToBasicUnsignedInteger());
                Bytecode.Seek(nextAddress - address - 2, SeekOrigin.Current);

                address = nextAddress;
            }

            // update line number dict
            foreach (var line in position.Deleteable)
            {
                _lineNumberMap.Remove(line);
            }

            foreach (var line in position.Beyond)
            {
                _lineNumberMap[line] += length;
            }
        }
Example #9
0
        private static Bytecode CreateGraphOp(string name, object value)
        {
            var bytecode = new Bytecode();

            bytecode.AddSource(name, value);
            return(bytecode);
        }
Example #10
0
        public TestTraversal(List <object> traverserObjs)
        {
            var traversers = new List <Traverser>(traverserObjs.Count);

            traverserObjs.ForEach(o => traversers.Add(new Traverser(o)));
            Traversers = traversers;
            Bytecode   = new Bytecode();
        }
Example #11
0
        public TestTraversal(IReadOnlyList <object> traverserObjs, IReadOnlyList <long> traverserBulks)
        {
            var traversers = new List <Traverser>(traverserObjs.Count);

            traversers.AddRange(traverserObjs.Select((t, i) => new Traverser(t, traverserBulks[i])));
            Traversers = traversers;
            Bytecode   = new Bytecode();
        }
Example #12
0
        public void CreateWithTwoOperands(byte opcode, int operand1, int operand2)
        {
            var actual = Bytecode.Create(opcode, new List <int> {
                operand1, operand2
            });

            Utilities.Assert.AreDeeplyEqual(actual, Fixtures.Bytecode.Opcodes[opcode]);
        }
 public void Create(string filename, Bytecode bytecode)
 {
     using (var stream = File.Open(filename, FileMode.Create))
     {
         var bFormatter = new BinaryFormatter();
         bFormatter.Serialize(stream, bytecode);
     }
 }
Example #14
0
        public void ShouldUseBindingsInsideArrayInStepArgument()
        {
            var bytecode = new Bytecode();
            var b        = Bindings.Instance;

            bytecode.AddStep("someStep", "test", new[] { b.Of("arrayVariable", "arrayValue") });

            Assert.Equal(new Binding("arrayVariable", "arrayValue"), bytecode.StepInstructions[0].Arguments[1]);
        }
Example #15
0
        public void ShouldUseBingingsForSimpleValueInStepArgument()
        {
            var bytecode = new Bytecode();
            var bindings = Bindings.Instance;

            bytecode.AddStep("hasLabel", bindings.Of("label", "testvalue"));

            Assert.Equal(new Binding("label", "testvalue"), bytecode.StepInstructions[0].Arguments[0]);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="SchemaBoundTraversal{S, E}"/> class.
        /// </summary>
        /// <param name="bytecode">The bytecode.</param>
        /// <exception cref="ArgumentNullException">bytecode</exception>
        public SchemaBoundTraversal(Bytecode bytecode)
        {
            if (bytecode == null)
            {
                throw new ArgumentNullException(nameof(bytecode));
            }

            Bytecode = bytecode;
        }
Example #17
0
 public bool Equals(Bytecode other)
 {
     if (other is Label)
     {
         var tmp = (Label)other;
         return(tmp.Location == this.Location);
     }
     return(false);
 }
Example #18
0
 public bool Equals(Bytecode other)
 {
     if (other is Save)
     {
         var tmp = (Save)other;
         return(tmp.Id == this.Id);
     }
     return(false);
 }
Example #19
0
 public bool Equals(Bytecode other)
 {
     if (other is Symbol)
     {
         var tmp = (Symbol)other;
         return(tmp.Lo == this.Lo && this.Hi == this.Hi);
     }
     return(false);
 }
Example #20
0
 public bool Equals(Bytecode other)
 {
     if (other is Fork)
     {
         var tmp = (Fork)other;
         return(tmp.Fst.Equals(this.Fst) && tmp.Snd.Equals(this.Snd) && tmp.Greedy == this.Greedy);
     }
     return(false);
 }
        public void ShouldThrowOriginalExceptionWhenByteCodeIsInvalid()
        {
            var testBytecode = new Bytecode();

            testBytecode.AddStep("V");
            testBytecode.AddStep("this_step_does_not_exist", "test");
            var testTraversal = CreateTraversalWithRemoteStrategy(testBytecode);

            Assert.Throws <ResponseException>(() => testTraversal.Next());
        }
Example #22
0
            public bool Equals(Bytecode other)
            {
                if (other is Jump)
                {
                    var tmp = (Jump)other;
                    return(tmp.Where.Equals(this.Where));
                }

                return(false);
            }
Example #23
0
        public void ShouldSerialize_g_V(int version)
        {
            var bytecode = new Bytecode();

            bytecode.AddStep("V");
            var graphsonWriter = CreateGraphSONWriter(version);

            var graphSON = graphsonWriter.WriteObject(bytecode);

            Assert.Equal("{\"@type\":\"g:Bytecode\",\"@value\":{\"step\":[[\"V\"]]}}", graphSON);
        }
Example #24
0
 public static IGremlinQuerySerializer ToGroovy(this IGremlinQuerySerializer serializer, GroovyFormatting formatting = GroovyFormatting.BindingsOnly)
 {
     return(serializer
            .Select(serialized => serialized switch
     {
         GroovyGremlinQuery serializedQuery => formatting == GroovyFormatting.AllowInlining
                 ? serializedQuery.Inline()
                 : serializedQuery,
         Bytecode byteCode => byteCode.ToGroovy(formatting),
         _ => throw new NotSupportedException($"Can't convert serialized query of type {serialized.GetType()} to {nameof(GroovyGremlinQuery)}.")
     }));
 void Push(Bytecode val)
 {
     if (stackSize > MAX_STACK)
     {
         Debug.Log("스택 오버플로 _ 오버");
     }
     else
     {
         cmdStack[stackSize++] = val;
     }
 }
 /// <inheritdoc/>
 protected override void Dispose(bool disposing)
 {
     if (disposing)
     {
         if (Bytecode != null)
         {
             Bytecode.Dispose();
             Bytecode = null;
         }
     }
 }
Example #27
0
        /// <summary>
        /// Erase the program from memory.
        /// </summary>
        public void Erase()
        {
            Bytecode.Clear();
            Bytecode.Write("\0\0\0");

            _protected     = false;
            _lastStored    = null;
            _lineNumberMap = new Dictionary <int, long>
            {
                { 65536, 0 }
            };
        }
Example #28
0
        public async Task <ITraversal <TStart, TEnd> > SubmitAsync <TStart, TEnd>(Bytecode bytecode)
        {
            var graphStatement = DseRemoteConnection.CreateStatement(bytecode, _graphOptions, true);
            var rs             = await _session.ExecuteGraphAsync(graphStatement).ConfigureAwait(false);

            var graphTraversal = new GraphTraversal <TStart, TEnd>
            {
                Traversers = GetTraversers <TEnd>(rs)
            };

            return(graphTraversal);
        }
Example #29
0
        public void ShouldUseBingings()
        {
            var bytecode = new Bytecode();
            var bindings = new Bindings();

            bytecode.AddStep("hasLabel", bindings.Of("label", "testLabel"));

            var arg     = bytecode.StepInstructions[0].Arguments[0];
            var binding = arg as Binding;

            Assert.Equal(new Binding("label", "testLabel"), binding);
        }
Example #30
0
        /// <summary>
        /// Store the given tokenized line buffer.
        /// </summary>
        private void StoreLine(Stream stream)
        {
            if (_protected)
            {
                throw new ReplRuntimeException(ReplExceptionCode.IllegalFunctionCall);
            }

            stream.Seek(1, SeekOrigin.Begin);
            var scanLine = stream.ReadLineNumber();

            // check if stream is an empty line after the line number
            var nextNonWhitespace = stream.SkipWhitespace();
            var empty             = nextNonWhitespace == -1 || nextNonWhitespace == '\0';
            var codePosition      = FindCodePosition(scanLine, scanLine);

            if (empty && codePosition.Deleteable.Length == 0)
            {
                throw new ReplRuntimeException(ReplExceptionCode.UndefinedLineNumber);
            }

            // read the remainder of the program into a buffer to be pasted back after the write
            Bytecode.Seek(codePosition.AfterPosition, SeekOrigin.Begin);
            var rest = Bytecode.ReadToEnd();

            Bytecode.Seek(codePosition.StartPosition, SeekOrigin.Begin);
            var length = 0;

            // write the line buffer to the program buffer
            if (!empty)
            {
                // set offsets
                length = stream.ReadToEnd().Length;
                stream.Seek(0, SeekOrigin.Begin); // pass \x00\xC0\xDE

                Bytecode.WriteByte(0);
                Bytecode.Write(((int)(Position + 1 + codePosition.StartPosition + length)).ToBasicUnsignedInteger());
                Bytecode.WriteByte((byte)stream.ReadByte());
            }

            // write back the remainder of the program
            Truncate(rest);

            // update all next offsets by shifting them by the length of the added line
            UpdateLineMap(codePosition, length);

            if (!empty)
            {
                _lineNumberMap[scanLine] = codePosition.StartPosition;
            }

            _lastStored = scanLine;
        }
Example #31
0
        public void Unserialize(GMDataReader reader)
        {
            Name   = reader.ReadStringPointerObject();
            Length = reader.ReadInt32();

            if (reader.VersionInfo.FormatID <= 14)
            {
                BytecodeEntry = new Bytecode(this);
                BytecodeEntry.Unserialize(reader, Length);
            }
            else
            {
                LocalsCount = reader.ReadInt16();
                int v = reader.ReadInt16();
                ArgumentsCount = (short)(v & 0b1111111111111);
                Flags          = (byte)(v >> 13);
                int  relativeBytecodeAddr = reader.ReadInt32();
                int  absoluteBytecodeAddr = (reader.Offset - 4) + relativeBytecodeAddr;
                bool childCandidate       = false;
                if (reader.PointerOffsets.TryGetValue(absoluteBytecodeAddr, out GMSerializable s))
                {
                    if (s is Bytecode b)
                    {
                        BytecodeEntry  = b;
                        childCandidate = true;
                    }
                }
                if (BytecodeEntry == null)
                {
                    BytecodeEntry = new Bytecode(this);
                    if (Length != 0) // prevent pointer overlap of entries with 0 instructions
                    {
                        reader.PointerOffsets[absoluteBytecodeAddr] = BytecodeEntry;
                    }

                    int returnTo = reader.Offset;
                    reader.Offset = absoluteBytecodeAddr;

                    BytecodeEntry.Unserialize(reader, Length);

                    reader.Offset = returnTo;
                }
                BytecodeOffset = reader.ReadInt32();

                if (childCandidate && Length != 0 && BytecodeOffset != 0)
                {
                    // Assign parents and children of this entry
                    ParentEntry = BytecodeEntry.Parent;
                    BytecodeEntry.Parent.ChildEntries.Add(this);
                }
            }
        }
Example #32
0
 public static IGremlinQuerySerializer ToGroovy(this IGremlinQuerySerializer serializer)
 {
     return(serializer
            .Select(serialized =>
     {
         return serialized switch
         {
             GroovyGremlinQuery serializedQuery => serializedQuery,
             Bytecode bytecode => bytecode.ToGroovy(),
             _ => throw new NotSupportedException($"Can't convert serialized query of type {serialized.GetType()} to {nameof(GroovyGremlinQuery)}.")
         };
     }));
 }
Example #33
0
 public virtual void Emit(Bytecode opcode)
 {
     Emit(null, opcode);
 }
Example #34
0
        public void Load(Bytecode bytecode)
        {
            var loader = new Loader(new AntlrRunnableBuilder {DebugInfo = Debug});

            var runnable = loader.Load(bytecode.Script);

            RuntimeContext = new RuntimeContext(runnable)
                                 {
                                     Hospedagem = Hospedagem,
                                     EnableGC = EnableGC
                                 };
        }
Example #35
0
        public void Load(string asm)
        {
            var bytecode = new Bytecode(asm.Split('\n'), null);

            Load(bytecode);
        }
Example #36
0
 public virtual void Emit1(CommonTree opAST, Bytecode opcode, string s)
 {
     int i = DefineString(s);
     Emit1(opAST, opcode, i);
 }
Example #37
0
 public void emit2(CommonTree opAST, Bytecode opcode, string s, int arg2)
 {
     CompilationState.Emit2(opAST, opcode, s, arg2);
 }
Example #38
0
 public void insert(int addr, Bytecode opcode, string s)
 {
     CompilationState.Insert(addr, opcode, s);
 }
Example #39
0
 public void emit(CommonTree opAST, Bytecode opcode)
 {
     CompilationState.Emit(opAST, opcode);
 }
Example #40
0
 public void emit1(CommonTree opAST, Bytecode opcode, string arg)
 {
     CompilationState.Emit1(opAST, opcode, arg);
 }
Example #41
0
 public void emit(Bytecode opcode)
 {
     CompilationState.Emit(opcode);
 }
Example #42
0
 public virtual void Emit2(CommonTree opAST, Bytecode opcode, int arg, int arg2)
 {
     Emit(opAST, opcode);
     EnsureCapacity(Instruction.OperandSizeInBytes * 2);
     WriteShort(impl.instrs, ip, (short)arg);
     ip += Instruction.OperandSizeInBytes;
     WriteShort(impl.instrs, ip, (short)arg2);
     ip += Instruction.OperandSizeInBytes;
 }
Example #43
0
 public virtual void Emit(CommonTree opAST, Bytecode opcode)
 {
     EnsureCapacity(1);
     if (opAST != null)
     {
         int i = opAST.TokenStartIndex;
         int j = opAST.TokenStopIndex;
         int p = tokens.Get(i).StartIndex;
         int q = tokens.Get(j).StopIndex;
         if (!(p < 0 || q < 0))
             impl.sourceMap[ip] = Interval.FromBounds(p, q + 1);
     }
     impl.instrs[ip++] = (byte)opcode;
 }
Example #44
0
 public virtual void Emit2(CommonTree opAST, Bytecode opcode, string s, int arg2)
 {
     int i = DefineString(s);
     Emit2(opAST, opcode, i, arg2);
 }
Example #45
0
 public virtual void Insert(int addr, Bytecode opcode, string s)
 {
     //System.out.println("before insert of "+opcode+"("+s+"):"+ Arrays.toString(impl.instrs));
     EnsureCapacity(1 + Instruction.OperandSizeInBytes);
     int instrSize = 1 + Instruction.OperandSizeInBytes;
     // make room for opcode, opnd
     Array.Copy(impl.instrs, addr, impl.instrs, addr + instrSize, ip - addr);
     int save = ip;
     ip = addr;
     Emit1(null, opcode, s);
     ip = save + instrSize;
     //System.out.println("after  insert of "+opcode+"("+s+"):"+ Arrays.toString(impl.instrs));
     // adjust addresses for BR and BRF
     int a = addr + instrSize;
     while (a < ip)
     {
         Bytecode op = (Bytecode)impl.instrs[a];
         Instruction I = Instruction.instructions[(int)op];
         if (op == Bytecode.INSTR_BR || op == Bytecode.INSTR_BRF)
         {
             int opnd = BytecodeDisassembler.GetShort(impl.instrs, a + 1);
             WriteShort(impl.instrs, a + 1, (short)(opnd + instrSize));
         }
         a += I.nopnds * Instruction.OperandSizeInBytes + 1;
     }
     //System.out.println("after  insert of "+opcode+"("+s+"):"+ Arrays.toString(impl.instrs));
 }