munificent / magpie
The Magpie programming language.
Clone this repository (size: 948.0 KB): HTTPS / SSH
$ hg clone http://bitbucket.org/munificent/magpie/
| commit 36: | 46d09f708b11 |
| parent 35: | d78a20a8a165 |
| branch: | default |
Random intrinsic.
| r36:46d09f708b11 | 409 loc | 14.9 KB | embed / history / annotate / raw / |
|---|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace Magpie.Interpreter
{
public class Machine
{
public event EventHandler<PrintEventArgs> Printed;
/// <summary>
/// Gets and sets the maximum stack depth. If set to a non-zero value, the interpreter
/// will track it during calls and immediately stop if the max is exceeded.
/// </summary>
public int MaxStackDepth { get; set; }
public Machine(IForeignRuntimeInterface foreignInterface)
{
mForeignInterface = foreignInterface;
}
public void Interpret(Stream stream)
{
BytecodeFile bytecode = new BytecodeFile(stream);
Interpret(bytecode, String.Empty);
}
public void Interpret(BytecodeFile file, string argument)
{
mFile = file;
// find "main"
Push(mFile.OffsetToMain);
Call(0, false);
Interpret();
}
public void Interpret(BytecodeFile file)
{
Interpret(file, String.Empty);
}
public void Interpret()
{
bool running = true;
while (running)
{
OpCode theOp = ReadOpCode();
//Console.WriteLine(theOp.ToString());
switch (theOp)
{
case OpCode.PushNull: Push((Structure)null); break;
case OpCode.PushBool: Push(ReadByte() != 0); break;
case OpCode.PushInt: Push(ReadInt()); break;
case OpCode.PushString: Push(mFile.ReadString(ReadInt())); break;
case OpCode.PushLocals: Push(mCurrentFrame); break;
case OpCode.Alloc:
{
int slots = ReadInt();
Structure structure = new Structure(slots);
// initialize it
// note: slots are on stack in reverse order
// because they have been pushed in forward order.
// this ensures that arguments are evaluated left to right.
// for example: calling Foo (1, 2, 3) will create the arg
// tuple by evaluating 1, 2, 3 in order. this leaves the
// stack (from top down) looking like 3 2 1.
for (int i = slots - 1; i >= 0; i--)
{
structure[i] = Pop();
}
Push(structure);
}
break;
case OpCode.Load:
{
byte index = ReadByte();
Structure struc = PopStructure();
Value op = struc[index];
Push(op);
}
break;
case OpCode.Store:
{
byte index = ReadByte();
Structure struc = PopStructure();
struc[index] = Pop();
}
break;
case OpCode.LoadArray:
{
Structure struc = PopStructure();
int index = struc[0].Int;
Structure array = struc[1].Struct;
//### bob: should bounds-check
// add one to skip the first slot which holds the array size
Push(array[index + 1]);
}
break;
case OpCode.StoreArray:
{
Structure struc = PopStructure();
int index = struc[0].Int;
Structure array = struc[1].Struct;
Value value = struc[2];
//### bob: should bounds-check
// add one to skip the first slot which holds the array size
array[index + 1] = value;
}
break;
case OpCode.SizeArray:
{
Structure struc = PopStructure();
// array size is the first element
Push(struc[0]);
}
break;
case OpCode.Call0: Call(0, false); break;
case OpCode.Call1: Call(1, false); break;
case OpCode.CallN: Call(2, false); break;
case OpCode.TailCall0: Call(0, true); break;
case OpCode.TailCall1: Call(1, true); break;
case OpCode.TailCallN: Call(2, true); break;
case OpCode.ForeignCall0: ForeignCall(0); break;
case OpCode.ForeignCall1: ForeignCall(1); break;
case OpCode.ForeignCallN: ForeignCall(2); break;
case OpCode.Return:
{
mInstruction = mCurrentFrame[mCurrentFrame.Count - 1].Int;
mCurrentFrame = mCurrentFrame[mCurrentFrame.Count - 2].Struct;
// stop completely if we've returned from main
if (mCurrentFrame == null) running = false;
}
break;
case OpCode.Jump: mInstruction = ReadInt(); break;
case OpCode.JumpIfFalse: int offset = ReadInt();
if (!PopBool()) mInstruction = offset;
break;
case OpCode.BoolToString: Push(PopBool() ? "true" : "false"); break;
case OpCode.IntToString: Push(PopInt().ToString()); break;
case OpCode.EqualBool:
{
Structure tuple = PopStructure();
Push(tuple[0].Bool == tuple[1].Bool);
}
break;
case OpCode.EqualInt:
{
Structure tuple = PopStructure();
Push(tuple[0].Int == tuple[1].Int);
}
break;
case OpCode.EqualString:
{
Structure tuple = PopStructure();
Push(tuple[0].String == tuple[1].String);
}
break;
case OpCode.LessInt:
{
Structure tuple = PopStructure();
Push(tuple[0].Int < tuple[1].Int);
}
break;
case OpCode.GreaterInt:
{
Structure tuple = PopStructure();
Push(tuple[0].Int > tuple[1].Int);
}
break;
case OpCode.NegateBool: Push(!PopBool()); break;
case OpCode.NegateInt: Push(-PopInt()); break;
case OpCode.AndBool:
{
Structure tuple = PopStructure();
Push(tuple[0].Bool && tuple[1].Bool);
}
break;
case OpCode.OrBool:
{
Structure tuple = PopStructure();
Push(tuple[0].Bool || tuple[1].Bool);
}
break;
case OpCode.AddInt:
{
Structure tuple = PopStructure();
Push(tuple[0].Int + tuple[1].Int);
}
break;
case OpCode.SubInt:
{
Structure tuple = PopStructure();
Push(tuple[0].Int - tuple[1].Int);
}
break;
case OpCode.MultInt:
{
Structure tuple = PopStructure();
Push(tuple[0].Int * tuple[1].Int);
}
break;
case OpCode.DivInt:
{
Structure tuple = PopStructure();
Push(tuple[0].Int / tuple[1].Int);
}
break;
case OpCode.Random:
{
// only create if needed
if (mRandom == null)
{
mRandom = new Random();
}
Push(mRandom.Next(PopInt()));
}
break;
case OpCode.AddString:
{
Structure tuple = PopStructure();
Push(tuple[0].String + tuple[1].String);
}
break;
case OpCode.Print:
string text = PopString();
if (Printed != null) Printed(this, new PrintEventArgs(text));
break;
case OpCode.StringSize: Push(PopString().Length); break;
case OpCode.Substring:
{
Structure tuple = PopStructure();
Push(tuple[0].String.Substring(tuple[1].Int, tuple[2].Int));
}
break;
default: throw new Exception("Unknown opcode.");
}
}
}
private OpCode ReadOpCode()
{
return (OpCode)mFile.Bytes[mInstruction++];
}
private byte ReadByte()
{
return mFile.Bytes[mInstruction++];
}
private char ReadChar()
{
int c = ((int)mFile.Bytes[mInstruction++]) |
((int)mFile.Bytes[mInstruction++] << 8);
return (char)c;
}
private int ReadInt()
{
return ((int)mFile.Bytes[mInstruction++]) |
((int)mFile.Bytes[mInstruction++] << 8) |
((int)mFile.Bytes[mInstruction++] << 16) |
((int)mFile.Bytes[mInstruction++] << 24);
}
private void Push(Value value) { mOperands.Push(value); }
private void Push(bool value) { Push(new Value(value)); }
private void Push(char value) { Push(new Value(value)); }
private void Push(int value) { Push(new Value(value)); }
private void Push(string value) { Push(new Value(value)); }
private void Push(Structure value) { Push(new Value(value)); }
private Value Pop() { return mOperands.Pop(); }
private bool PopBool() { return mOperands.Pop().Bool; }
private int PopInt() { return mOperands.Pop().Int; }
private string PopString() { return mOperands.Pop().String; }
private Structure PopStructure() { return mOperands.Pop().Struct; }
private Structure MakeCallFrame(int numLocals, Structure parentFrame, int instruction)
{
var frame = new Structure(numLocals + 2);
frame[numLocals] = new Value(parentFrame);
frame[numLocals + 1] = new Value(instruction);
return frame;
}
private void Call(int paramType, bool isTailCall)
{
// jump to the function
int previousInstruction = mInstruction;
mInstruction = PopInt();
int numLocals = ReadInt();
// if it's a tail call, discard the parent frame
//### bob: not tested. compiler doesn't emit tail calls yet
var parent = mCurrentFrame;
if (isTailCall)
{
parent = mCurrentFrame[mCurrentFrame.Count - 2].Struct;
previousInstruction = mCurrentFrame[mCurrentFrame.Count - 1].Int;
}
mCurrentFrame = MakeCallFrame(numLocals, parent, previousInstruction);
// pop and store the argument
if (paramType != 0) mCurrentFrame[0] = Pop();
// track stack depth
if (MaxStackDepth != 0)
{
int stackDepth = GetStackDepth(mCurrentFrame);
if (stackDepth > MaxStackDepth) throw new MaxStackDepthExceededException(MaxStackDepth);
}
}
private void ForeignCall(int paramType) // (int id, Value[] args)
{
int id = ReadInt();
Value[] args;
switch (paramType)
{
case 0: args = new Value[0]; break;
case 1: args = new Value[] { Pop() }; break;
case 2: args = PopStructure().Fields.ToArray(); break;
default: throw new ArgumentException("Unknown parameter type.");
}
Value result = mForeignInterface.ForeignCall(id, args);
if (result != null) Push(result);
}
private int GetStackDepth(Structure callFrame)
{
if (callFrame == null) return 0;
return 1 + GetStackDepth(callFrame[callFrame.Count - 2].Struct);
}
private BytecodeFile mFile;
//### bob: could also just store this in the current frame
private int mInstruction; // position in bytecode file
private readonly Stack<Value> mOperands = new Stack<Value>();
// call frame for the current function
// contains:
// 0 ... n: local variables
// n + 1 : reference to parent call frame
// n + 2 : instruction pointer for parent frame
private Structure mCurrentFrame;
private Random mRandom;
private readonly IForeignRuntimeInterface mForeignInterface;
}
}
|
