From 9fc64bbc95bb4e55f28f5262d0f5c660177f0a19 Mon Sep 17 00:00:00 2001 From: "Kartik K. Agaram" Date: Wed, 18 Feb 2015 14:46:30 -0800 Subject: 781 - first instruction to run in literate C++ version --- cpp/literate/009includes | 1 + cpp/literate/010vm | 2 +- cpp/literate/011load | 5 +++-- cpp/literate/012run | 41 +++++++++++++++++++++++++++++++++++++++++ 4 files changed, 46 insertions(+), 3 deletions(-) create mode 100644 cpp/literate/012run diff --git a/cpp/literate/009includes b/cpp/literate/009includes index c49c6c21..5c9a8d65 100644 --- a/cpp/literate/009includes +++ b/cpp/literate/009includes @@ -2,6 +2,7 @@ // More tightly-targeted includes show up in other files. :(before "End Includes") +#include #include #include #include diff --git a/cpp/literate/010vm b/cpp/literate/010vm index 4ae5c16a..3b8a7c96 100644 --- a/cpp/literate/010vm +++ b/cpp/literate/010vm @@ -11,7 +11,7 @@ int Next_recipe_number = 1; // Recipes are lists of instructions. To run a recipe, the computer runs its // instructions. struct recipe { - vector step; + vector steps; }; :(before "struct recipe") diff --git a/cpp/literate/011load b/cpp/literate/011load index 4bc73365..f2855e5f 100644 --- a/cpp/literate/011load +++ b/cpp/literate/011load @@ -9,7 +9,7 @@ recipe main [ +parse: product: {name: "1", type: 1} :(code) -void add_recipe(string form) { +int add_recipe(string form) { istringstream in(form); in >> std::noskipws; @@ -29,8 +29,9 @@ void add_recipe(string form) { instruction curr; while (next_instruction(in, &curr)) { - Recipe[r].step.push_back(curr); + Recipe[r].steps.push_back(curr); } + return r; } bool next_instruction(istream& in, instruction* curr) { diff --git a/cpp/literate/012run b/cpp/literate/012run new file mode 100644 index 00000000..f7b5469a --- /dev/null +++ b/cpp/literate/012run @@ -0,0 +1,41 @@ +:(scenarios run) +:(scenario copy_literal) +recipe main [ + 1:integer <- copy 23:literal +] ++run: instruction 0 ++run: ingredient 23 ++mem: storing in location 1 + +:(code) +void run(string form) { + run(add_recipe(form)); +} + +void run(recipe_number r) { + vector& instructions(Recipe[r].steps); + int n = 0; + vector::iterator p; + for (n = 0, p = instructions.begin(); p != instructions.end(); ++p, ++n) { + trace("run") << "instruction " << n; + switch (p->operation) { + case 1: { // copy + int arg = to_int(p->ingredients[0].name); + trace("run") << " ingredient " << arg; + int dest = to_int(p->products[0].name); + trace("mem") << " storing in location " << dest; + Memory[dest] = arg; + break; + } + default: + raise << "undefined operation " << p->operation; + } + } +} + +int to_int(string n) { + char* end = NULL; + int result = strtol(n.c_str(), &end, /*any base*/0); + assert(*end == '\0'); + return result; +} -- cgit 1.4.1-2-gfad0 href='#n6'>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