Skip to content

Commit

Permalink
02: Interpreters
Browse files Browse the repository at this point in the history
  • Loading branch information
lorentzimys committed Apr 13, 2024
1 parent 5f66758 commit ed31fa2
Show file tree
Hide file tree
Showing 2 changed files with 128 additions and 0 deletions.
71 changes: 71 additions & 0 deletions 02-Interpreters/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
const instructions = {
'SET A': 0,
'PRINT A': 1,
'IFN A': 2,
'RET': 3,
'DEC A': 4,
'JMP': 5
};

const program = [
// Ставим значения аккумулятора
instructions['SET A'],
// В 10
10,

// Выводим значение на экран
instructions['PRINT A'],

// Если A равно 0
instructions['IFN A'],

// Программа завершается
instructions['RET'],

// И возвращает 0
0,

// Уменьшаем A на 1
instructions['DEC A'],

// Устанавливаем курсор выполняемой инструкции
instructions['JMP'],

// В значение 2
2
];

function execute(code) {
let acc = 0;
let i = 0;

while (true) {
switch (code[i]) {
case reg['SET A']:
acc = code[i+1];
i += 2;
break;
case reg['PRINT A']:
console.log(acc);
++i;
break;
case reg['IFN A']:
if (acc === 0) {
++i;
} else {
i += 2;
}
break;
case reg['DEC A']:
--acc;
++i
break;
case reg['JMP']:
i = code[i+1]
break;
case reg['RET']:
return acc;
}
}
}
execute([0, 10, 1, 2, 3, 4, 5, 2])
57 changes: 57 additions & 0 deletions 02-Interpreters/База#2. ДЗ.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
# ДЗ к лекции База#2

## Придумать простой формат "байткода" и написать для него интерпретатор

```
const instructions = {
'SET A': 0,
'PRINT A': 1,
'IFN A': 2,
'RET': 3,
'DEC A': 4,
'JMP': 5
};
const program = [
// Ставим значения аккумулятора
instructions['SET A'],
// В 10
10,
// Выводим значение на экран
instructions['PRINT A'],
// Если A равно 0
instructions['IFN A'],
// Программа завершается
instructions['RET'],
// И возвращает 0
0,
// Уменьшаем A на 1
instructions['DEC A'],
// Устанавливаем курсор выполняемой инструкции
instructions['JMP'],
// В значение 2
2
];
// Выведет в консоль
// 10
// 9
// 8
// 7
// 6
// 5
// 4
// 3
// 2
// 1
// 0
// И вернет 0
execute(program);
```

0 comments on commit ed31fa2

Please sign in to comment.