Long time no see

This commit is contained in:
2026-02-21 10:47:00 +07:00
parent 0d54fe176e
commit b7df98a55c
198 changed files with 3249 additions and 1 deletions
+12
View File
@@ -0,0 +1,12 @@
void inc(int *p){(*p)++;}
void dec(int *p){(*p)--;}
int main(){
int x=10;
inc(&x);
dec(&x);
return 0;
}
+350
View File
@@ -0,0 +1,350 @@
# Генерация и анализ ассемблерного кода программы на C
---
## main.c
```c
void inc(int *p){(*p)++;}
void dec(int *p){(*p)--;}
int main(){
int x=10;
inc(&x);
dec(&x);
return 0;
}
```
---
## linux_x86_64_numbered.s
```asm
1 .file "main.c"
2 .text
3 .globl inc
4 .type inc, @function
5 inc:
6 .LFB0:
7 .cfi_startproc
8 pushq %rbp
9 .cfi_def_cfa_offset 16
10 .cfi_offset 6, -16
11 movq %rsp, %rbp
12 .cfi_def_cfa_register 6
13 movq %rdi, -8(%rbp)
14 movq -8(%rbp), %rax
15 movl (%rax), %eax
16 leal 1(%rax), %edx
17 movq -8(%rbp), %rax
18 movl %edx, (%rax)
19 nop
20 popq %rbp
21 .cfi_def_cfa 7, 8
22 ret
23 .cfi_endproc
24 .LFE0:
25 .size inc, .-inc
26 .globl dec
27 .type dec, @function
28 dec:
29 .LFB1:
30 .cfi_startproc
31 pushq %rbp
32 .cfi_def_cfa_offset 16
33 .cfi_offset 6, -16
34 movq %rsp, %rbp
35 .cfi_def_cfa_register 6
36 movq %rdi, -8(%rbp)
37 movq -8(%rbp), %rax
38 movl (%rax), %eax
39 leal -1(%rax), %edx
40 movq -8(%rbp), %rax
41 movl %edx, (%rax)
42 nop
43 popq %rbp
44 .cfi_def_cfa 7, 8
45 ret
46 .cfi_endproc
47 .LFE1:
48 .size dec, .-dec
49 .globl main
50 .type main, @function
51 main:
52 .LFB2:
53 .cfi_startproc
54 pushq %rbp
55 .cfi_def_cfa_offset 16
56 .cfi_offset 6, -16
57 movq %rsp, %rbp
58 .cfi_def_cfa_register 6
59 subq $16, %rsp
60 movq %fs:40, %rax
61 movq %rax, -8(%rbp)
62 xorl %eax, %eax
63 movl $10, -12(%rbp)
64 leaq -12(%rbp), %rax
65 movq %rax, %rdi
66 call inc
67 leaq -12(%rbp), %rax
68 movq %rax, %rdi
69 call dec
70 movl $0, %eax
71 movq -8(%rbp), %rdx
72 subq %fs:40, %rdx
73 je .L5
74 call __stack_chk_fail@PLT
75 .L5:
76 leave
77 .cfi_def_cfa 7, 8
78 ret
79 .cfi_endproc
80 .LFE2:
81 .size main, .-main
82 .ident "GCC: (GNU) 15.2.1 20251112"
83 .section .note.GNU-stack,"",@progbits
```
---
# windows_x86_64_numbered.s
```asm
1 .file "main.c"
2 .text
3 .globl inc
4 .def inc; .scl 2; .type 32; .endef
5 .seh_proc inc
6 inc:
7 pushq %rbp
8 .seh_pushreg %rbp
9 movq %rsp, %rbp
10 .seh_setframe %rbp, 0
11 .seh_endprologue
12 movq %rcx, 16(%rbp)
13 movq 16(%rbp), %rax
14 movl (%rax), %eax
15 leal 1(%rax), %edx
16 movq 16(%rbp), %rax
17 movl %edx, (%rax)
18 nop
19 popq %rbp
20 ret
21 .seh_endproc
22 .globl dec
23 .def dec; .scl 2; .type 32; .endef
24 .seh_proc dec
25 dec:
26 pushq %rbp
27 .seh_pushreg %rbp
28 movq %rsp, %rbp
29 .seh_setframe %rbp, 0
30 .seh_endprologue
31 movq %rcx, 16(%rbp)
32 movq 16(%rbp), %rax
33 movl (%rax), %eax
34 leal -1(%rax), %edx
35 movq 16(%rbp), %rax
36 movl %edx, (%rax)
37 nop
38 popq %rbp
39 ret
40 .seh_endproc
41 .globl main
42 .def main; .scl 2; .type 32; .endef
43 .seh_proc main
44 main:
45 pushq %rbp
46 .seh_pushreg %rbp
47 movq %rsp, %rbp
48 .seh_setframe %rbp, 0
49 subq $48, %rsp
50 .seh_stackalloc 48
51 .seh_endprologue
52 call __main
53 movl $10, -4(%rbp)
54 leaq -4(%rbp), %rax
55 movq %rax, %rcx
56 call inc
57 leaq -4(%rbp), %rax
58 movq %rax, %rcx
59 call dec
60 movl $0, %eax
61 addq $48, %rsp
62 popq %rbp
63 ret
64 .seh_endproc
65 .def __main; .scl 2; .type 32; .endef
66 .ident "GCC: (GNU) 15.2.0"
```
---
# riscv64_numbered.s
```asm
1 .file "main.c"
2 .option pic
3 .attribute arch, "rv64i2p1_m2p0_a2p1_f2p2_d2p2_c2p0_zicsr2p0_zifencei2p0_zmmul1p0_zaamo1p0_zalrsc1p0_zca1p0_zcd1p0"
4 .attribute unaligned_access, 0
5 .attribute stack_align, 16
6 .text
7 .align 1
8 .globl inc
9 .type inc, @function
10 inc:
11 .LFB0:
12 .cfi_startproc
13 addi sp,sp,-32
14 .cfi_def_cfa_offset 32
15 sd ra,24(sp)
16 sd s0,16(sp)
17 .cfi_offset 1, -8
18 .cfi_offset 8, -16
19 addi s0,sp,32
20 .cfi_def_cfa 8, 0
21 sd a0,-24(s0)
22 ld a5,-24(s0)
23 lw a5,0(a5)
24 addiw a5,a5,1
25 sext.w a4,a5
26 ld a5,-24(s0)
27 sw a4,0(a5)
28 nop
29 ld ra,24(sp)
30 .cfi_restore 1
31 ld s0,16(sp)
32 .cfi_restore 8
33 .cfi_def_cfa 2, 32
34 addi sp,sp,32
35 .cfi_def_cfa_offset 0
36 jr ra
37 .cfi_endproc
38 .LFE0:
39 .size inc, .-inc
40 .align 1
41 .globl dec
42 .type dec, @function
43 dec:
44 .LFB1:
45 .cfi_startproc
46 addi sp,sp,-32
47 .cfi_def_cfa_offset 32
48 sd ra,24(sp)
49 sd s0,16(sp)
50 .cfi_offset 1, -8
51 .cfi_offset 8, -16
52 addi s0,sp,32
53 .cfi_def_cfa 8, 0
54 sd a0,-24(s0)
55 ld a5,-24(s0)
56 lw a5,0(a5)
57 addiw a5,a5,-1
58 sext.w a4,a5
59 ld a5,-24(s0)
60 sw a4,0(a5)
61 nop
62 ld ra,24(sp)
63 .cfi_restore 1
64 ld s0,16(sp)
65 .cfi_restore 8
66 .cfi_def_cfa 2, 32
67 addi sp,sp,32
68 .cfi_def_cfa_offset 0
69 jr ra
70 .cfi_endproc
71 .LFE1:
72 .size dec, .-dec
73 .align 1
74 .globl main
75 .type main, @function
76 main:
77 .LFB2:
78 .cfi_startproc
79 addi sp,sp,-32
80 .cfi_def_cfa_offset 32
81 sd ra,24(sp)
82 sd s0,16(sp)
83 .cfi_offset 1, -8
84 .cfi_offset 8, -16
85 addi s0,sp,32
86 .cfi_def_cfa 8, 0
87 li a5,10
88 sw a5,-20(s0)
89 addi a5,s0,-20
90 mv a0,a5
91 call inc
92 addi a5,s0,-20
93 mv a0,a5
94 call dec
95 li a5,0
96 mv a0,a5
97 ld ra,24(sp)
98 .cfi_restore 1
99 ld s0,16(sp)
100 .cfi_restore 8
101 .cfi_def_cfa 2, 32
102 addi sp,sp,32
103 .cfi_def_cfa_offset 0
104 jr ra
105 .cfi_endproc
106 .LFE2:
107 .size main, .-main
108 .ident "GCC: (GNU) 15.1.0"
109 .section .note.GNU-stack,"",@progbits
```
---
## INFO
---
### gcc_version
gcc (GCC) 15.2.1 20251112
Copyright (C) 2025 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
---
### linux_gcc_version
gcc (GCC) 15.2.1 20251112
Copyright (C) 2025 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
---
### mingw_version
x86_64-w64-mingw32-gcc (GCC) 15.2.0
Copyright (C) 2025 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
---
### riscv_version
riscv64-linux-gnu-gcc (GCC) 15.1.0
Copyright (C) 2025 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
---
### sysinfo
Linux archlinux 6.17.8-arch1-1 #1 SMP PREEMPT_DYNAMIC Fri, 14 Nov 2025 06:54:20 +0000 x86_64 GNU/Linux
NAME="Arch Linux"
PRETTY_NAME="Arch Linux"
ID=arch
BUILD_ID=rolling
ANSI_COLOR="38;2;23;147;209"
HOME_URL="https://archlinux.org/"
DOCUMENTATION_URL="https://wiki.archlinux.org/"
SUPPORT_URL="https://bbs.archlinux.org/"
BUG_REPORT_URL="https://gitlab.archlinux.org/groups/archlinux/-/issues"
PRIVACY_POLICY_URL="https://terms.archlinux.org/docs/privacy-policy/"
LOGO=archlinux-logo
+92
View File
@@ -0,0 +1,92 @@
#include <stdio.h>
void pt(int prog[], int cmd,int acc,int pc);
int main() {
int prog[] = {
2, 5, // load 5
3, 3, // mult 3
1, // print acc
4, 7, // jump 7
2, 0, // load 0
5, 11,// jz 11
2, 2, // load 2
5, 1, // jz 1
3, 4, // mul 4
1, // print
0 // stop
};
int cmd, pc, acc;
cmd = pc = acc = 0;
while(pc != -1){
cmd = prog[pc];
switch(cmd){
case 0: //Проверка на команду остановки
printf("STOP\t ACC = %d\t PC = %d",acc,pc);
pc = -1;
break;
case 1: // Комманда 1 - вывод регистра
pt(prog,cmd,acc,pc);
pc++;
break;
case 2: // Комманда 2 - Присвоить регистру число
acc = prog[pc+1];// из след ячейки памяти
pt(prog,cmd,acc,pc);
pc+=2;
break;
case 3: // Комманда 3 - Умножить регистр на число
acc *= prog[pc+1];// в след ячейке памяти
pt(prog,cmd,acc,pc);
pc +=2;
break;
case 4: // Комманда 4 - Безусловный переход на указанную
pt(prog,cmd,acc,pc); // ячейку памяти
pc = prog[pc+1];
break;
case 5: // Комманда 5 - Переход на указанную ячейку
pt(prog,cmd,acc,pc);// памяти если регистр равен 0
if(acc == 0){pc = prog[pc+1];}
else(pc+=2);
break;
default: printf("err\n");return 1; // Защита от неправильной комманды
// и бесконечного зацикливания
}
}
return 0;
}
// Блок отвечающий за вывод в терминал
// значиний в момент выполнения комманд
void pt(int prog[],int cmd,int acc,int pc){
printf("\n");
printf("cmd: %d\n",cmd);
switch(cmd){
case 1:
printf("\tPrint acc\n\t\tacc = %d\n",acc);
printf("\t\tcurr pc = %d",pc);break;
case 2:
printf("\tLoad acc\n\t\tacc = %d\n",acc);
printf("\t\tcurr pc = %d",pc);break;
case 3:
printf("\tMult acc\n\t\tacc = %d\n",acc);
printf("\t\tcurr pc = %d",pc);break;
case 4:
printf("\tJump to\n\t\tto = %d\n",prog[pc+1]);
printf("\t\tcurr pc = %d",pc);break;
case 5:
if(acc==0){
printf("\tJump to if acc zero\n\t\tto = %d\n",prog[pc+1]);
}else(printf("\tJump to if acc zero\n\t\tacc != 0\n"));
printf("\t\tcurr pc = %d",pc);
break;
}
printf("\n");
}
+146
View File
@@ -0,0 +1,146 @@
#include <stdio.h>
#include <string.h>
int scan(void);
unsigned long func(int n);
void output(unsigned long sum);
void encr(unsigned long sum, char *cpum);
int cpumodel(char cpum[]);
int main() {
int n;
unsigned long isum;
char cpum[64];
cpumodel(cpum);
printf("Buff: ");
if (getchar() == '0') {
setbuf(stdin, NULL);
printf("buff is off\n");
} else {
printf("buff is on\n");
}
while(getchar()!='\n');
n = scan();
if(n == 0) return 0;
isum = func(n);
output(isum);
encr(isum,cpum);
return 0;
}
int scan(void){
int x, n;
n = 0;
printf("Enter num: 1-100 000\nNum: ");
while(((x = getchar())!='\n') && x != EOF){
if((x >= '0') && (x <= '9')){
n = (n*10) + (x-'0');
}
else{
if(x == '\n');
else(printf("Err \"%c\" is not a num.\n",x));
while((x = getchar())!='\n')
if(x == EOF) return 0;
printf("Num: ");
n = 0;
continue;
}
if(n > 100000){
while((x = getchar())!='\n')
if(x == EOF) return 0;
n = 0;
printf("You enter n>100 000 Try again\nNum: ");
continue;
}
if(x=='0'&&n<=0){
while((x = getchar())!='\n')
if(x == EOF) return 0;
printf("You num cannot starts with 0. Try again\nNum: ");
continue;
}
}
if (x == EOF) return 0;
return(n);
}
unsigned long func(int n){
int i;
unsigned long sum = 0;
unsigned char mem[65536];
char data[256 * 1024];
for(i = 1; i <= n; i++){
sum += i;
mem[i%65536] = (unsigned char)(i % 256);
data[i%(256*1024)] = (unsigned char)((sum + i) % 256U);
}
return sum;
}
void output(unsigned long sum){
int i = 0;
char buf[20];
printf("\nresult: ");
while(sum > 0){
buf[i++] = (char)('0' + (sum % 10));
sum /= 10;
}
while (i-- > 0)
putchar(buf[i]);
putchar('\n');
}
int cpumodel(char cpum[]) {
int c, i = 0;
printf("\nEnter proc name: ");
while ((c = getchar()) != '\n' && c != EOF && i < 64 - 1) {
cpum[i++] = (char)c;
}
cpum[i] = '\0';
return i;
}
void encr(unsigned long sum, char *cpum) {
char buf[20];
int i = 0;
int cpu_len = strlen(cpum);
if (cpu_len == 0) {
printf("CPU model is empty!\n");
return;
}
if (sum == 0) {
buf[i++] = '0';
} else {
while (sum > 0) {
buf[i++] = '0' + (sum % 10);
sum /= 10;
}
}
printf("enc result: ");
for (int j = i - 1; j >= 0; j--) {
int digit = buf[j] - '0';
char cpu_char = cpum[(i - 1 - j) % cpu_len];
int enc = (digit + (int)cpu_char) % 10;
putchar('0' + enc);
}
putchar('\n');
}
@@ -0,0 +1 @@
AMD Ryzen 5 5600X 6-Core Processor
@@ -0,0 +1,24 @@
model name : AMD Ryzen 5 5600X 6-Core Processor
cache size : 512 KB
cpu cores : 6
MemTotal: 16293648 kB
Caches (sum of all):
L1d: 192 KiB (6 instances)
L1i: 192 KiB (6 instances)
L2: 3 MiB (6 instances)
L3: 32 MiB (1 instance)
Кэш‑память расположена близко к ядрам процессора (обычно в том же кристалле), поэтому доступ к ней происходит за несколько тактов процессора, тогда как доступ к оперативной памяти требует десятки‑сот тактов из‑за физической дистанции, шины и контроллера памяти.
Параметр Кэш L1/L2/L3 Оперативная RAM
Время доступа 1–5 такт(ов) 50–150 такт(ов)
Емкость десятки‑сот КБ несколько ГБ
Стоимость (энергия/площадь) Высокая Низкая
Ryzen 55600X
Тактовая частота ядра: ~4.6 ГГц → один такт ≈ 0.22 нс.
Время доступа к L1: ~4 такт ≈ 0.9 нс.
Время доступа к DDR4‑3200 RAM: ~70 такт ≈ 15 нс.
Если 95 % инструкций и данных находятся в кэше, среднее время доступа будет близко к 1 нс, а не к 15 нс, что делает процессор эффективным несмотря на медленную RAM.
+34
View File
@@ -0,0 +1,34 @@
#!/bin/bash
HOMECPU="homecpu.txt"
CURRENTCPU=$(grep -m1 'model name' /proc/cpuinfo | awk -F':' '{print $2}' | sed -E 's/^[ \t]+//')
# Извлекаем только модель (например, i7-9700K из полного названия)
EXTRACT_MODEL() {
echo "$1" | grep -oE '[iI]ntel|[aA]md|[iI][0-9]*-[0-9A-Z]*|[rR]yzen|[0-9A-Z]*-[0-9A-Z]*' | head -1
}
CURRENT_MODEL=$(EXTRACT_MODEL "$CURRENTCPU")
gcc ./code.c -o ./run
if [ ! -f "$HOMECPU" ]; then
echo "Домашняя модель CPU не найдена, используем текущую: $CURRENT_MODEL"
CPUMODEL="$CURRENT_MODEL"
else
HOMECPU_CONTENT=$(<"$HOMECPU")
HOME_MODEL=$(EXTRACT_MODEL "$HOMECPU_CONTENT")
echo "Домашняя модель CPU: $HOME_MODEL"
echo "Текущая модель CPU: $CURRENT_MODEL"
if [ "$CURRENT_MODEL" = "$HOME_MODEL" ]; then
echo "Модели совпадают, используем текущую модель"
CPUMODEL="$CURRENT_MODEL"
else
echo "Модели не совпадают, используем домашнюю модель"
CPUMODEL="$HOME_MODEL"
fi
fi
# Отправляем модель CPU и ввод для программы
( printf "%s\n1\n" "$CPUMODEL"; cat ) | ./run
+1
View File
@@ -0,0 +1 @@
15
+22
View File
@@ -0,0 +1,22 @@
global_var = 10
neg_num = -5
result = global_var + neg_num
user_age = int(input())
if global_var >= 5:
result = result + 1
if neg_num <= 0:
print("Negatine num\n")
counter = 0
while counter <= 3:
print(counter)
counter += 1
for i in range(10):
result = result + 1
print(result)
print(user_age)
+317
View File
@@ -0,0 +1,317 @@
#include <stdio.h>
#include <wchar.h>
#include <locale.h>
#define MAXINPUTARRAY 1000
#define MAXKNOWN 30
#define MAXROW 40
#define CMDLIST 4
#define CMDCOUNT 6
int it_is_what(wchar_t ch);
int main(){
setlocale(LC_ALL, "");
wchar_t massive[MAXINPUTARRAY] = {0};
wchar_t knownint[MAXKNOWN] = {0};
int CellsInMainArray = 0;
{ // GET ALL INPUT
wchar_t ch;
while((ch = getwchar()) != WEOF){
massive[CellsInMainArray]=ch;
CellsInMainArray++;
if(CellsInMainArray>=MAXINPUTARRAY)
return 1100;
}
}
{ // IS X(LETTER) EXISIST?
int k = 0;
while(k++ < CellsInMainArray){
if((massive[k] >= 'a' && massive[k] <= 'z') &&
massive[k+1]==' ' &&
!(massive[k-1] >= 'a' && massive[k-1] <= 'z')){
int mark = 1;
for(int i = 0;i<MAXKNOWN-1;i++){
if(massive[k]==knownint[i])mark=0;
}
if(mark){
putwchar(L'i'); putwchar(L'n');
putwchar(L't');putwchar(L' ');
putwchar(massive[k]); putwchar(' ');
putwchar('='); putwchar(' ');
putwchar('0'); putwchar(';'); putwchar('\n');
knownint[knownint[MAXKNOWN-1]] = massive[k];knownint[MAXKNOWN-1]++;
}
}
}
putwchar('\n');putwchar('\n');
}
int massiveCursor = 0;
wchar_t row[MAXROW] = {0};
int deathMark = 1;
do{
int command = 0;
int rowCursor = 0;
{// GET ROW
{ // CLEAR ROW
for(int i=0; i<MAXROW; i++) row[i] = ' ';
rowCursor = 0;
}
{ // GET ROW
while(massiveCursor < CellsInMainArray && rowCursor < MAXROW &&
massive[massiveCursor] != '\n' && row[rowCursor] != WEOF){
row[rowCursor] = massive[massiveCursor];
massiveCursor++;
rowCursor++;
if(massive[massiveCursor] == '\0' ||
massive[massiveCursor] == WEOF){
deathMark = 0;
}
}
massiveCursor++;
rowCursor++;
}
if(massiveCursor>MAXINPUTARRAY)return 0;
}
{ // TEST FOR COMMENT AND \t \n ' '
{
if(row[0]=='#'){
int i = 0;
putwchar('/');putwchar('/');
while(i++ < rowCursor)putwchar(row[i]);
putwchar('\n');
continue;
}
}
{
int i = 0;
if(row[0] == WEOF) return 0;
if(rowCursor<4){
while(i < rowCursor) putwchar(row[i++]);
continue;}
}
{
while(row[0]=='\t' || row[0] == ' '){
putwchar(row[0]);
for(int i = 0;i<rowCursor;i++){
row[i]=row[i+1];
}
rowCursor--;
}
}
}
{ //Test for see what command is it
wchar_t cmd[CMDLIST][CMDCOUNT] = {L"if",L"while",L"for",L"print"};
for(int i = 0;i<CMDLIST;i++){
int marker = 0;
int symbCount = 0;
for(int k = 0;cmd[i][k]!='\0';k++){
symbCount++;
}
for(int k = 0;k < symbCount;k++){
if(row[k]==cmd[i][k]){
marker++;
}
if (symbCount == marker && symbCount != 0){
command = i+1;
break;
}
}
if(command!= 0) break;
}
}
{//PRINT x = something;
if(it_is_what(row[0])==0 && // Enter if its letter
(it_is_what(row[2])==8 || // and logic
it_is_what(row[2])==9)){ // or arfimetic
wchar_t pyinput[] = L"int(input())";
int marker = 1,i=0;
while(pyinput[i++]!='\0'){
if(row[i+4]!=pyinput[i])marker=0;
}
if(marker){
wchar_t cinput[] = {L"scanf(\"%d\", &"};
i = 0;
while(cinput[i]!='\0')
putwchar(cinput[i++]);
putwchar(row[0]);putwchar(')');putwchar(';');putwchar('\n');
}
else{
for(int i = 0;i<rowCursor;i++){
if(row[i]=='\n')row[i]='\0';
putwchar(row[i]);
}
putwchar(';');putwchar('\n');
}
continue;
}
}
switch(command){ //COMMANDS
case 1:{ // IF if x > 0:
{ // PRINT PRE LETTERS
wchar_t word[] = L"if(";
int i = 0;
while(word[i]!='\0')putwchar(word[i++]);
}
{ // IF FUNC
int xpos = 3;
putwchar(row[xpos]);// x
putwchar(row[xpos+2]);// >
// >=
int tmp = 0;
if(it_is_what(row[xpos+3])==8){putwchar(row[xpos+3]);tmp++;}
// NUM
for(int i = xpos+4+tmp;i<rowCursor;i++){
if(it_is_what(row[i])==2) putwchar(row[i]);
}
}
{ // PRINT POST LETTERS
wchar_t word[] = L")\n";
int i = 0;
while(word[i]!='\0')putwchar(word[i++]);
}
break;
} // if(x > 0)
case 2:{ // WHILE while i < 10:
{ // PRINT PRE LETTERS
wchar_t word[] = L"while(";
int i = 0;
while(word[i]!='\0')putwchar(word[i++]);
}
{ // WHILE FUNC
int xpos = 6;
putwchar(row[xpos]);// i
putwchar(row[xpos+2]);// >
// >=
int tmp = 0;
if(it_is_what(row[xpos+3])==8){putwchar(row[xpos+3]);tmp++;}
// NUM
for(int i = xpos+4+tmp;i<rowCursor;i++){
if(it_is_what(row[i])==2) putwchar(row[i]);
}
}
{ // PRINT POST LETTERS
wchar_t word[] = L")\n";
int i = 0;
while(word[i]!='\0')putwchar(word[i++]);
}
break;
} // while(i < 10)
case 3:{ // FOR for i in range (10):
{ // PRINT PRE LETTERS
wchar_t word[] = L"for(int ";
int i = 0;
while(word[i]!='\0')putwchar(word[i++]);
}
{ // FOR FUNC
int xpos = 4;
putwchar(row[xpos]);
wchar_t word[] = L" = 0;i < ";
int i = 0;
while(word[i]!='\0')putwchar(word[i++]);
// NUM
for(int i = xpos+11;i<rowCursor;i++)
if(it_is_what(row[i])==2) putwchar(row[i]);
}
{ // PRINT POST LETTERS
wchar_t word[] = L";i++)\n";
int i = 0;
while(word[i]!='\0')putwchar(word[i++]);
}
break;
} // for(int i = 0;i<10;i++)
case 4:{ // PRINT print(L"letters")
{ // PRINT PRE LETTERS
wchar_t word[] = {L"printf(\""};
int i = 0;
while(word[i]!='\0')putwchar(word[i++]);
}
{ // PRINT FUNC
int xpos = 6;
if(it_is_what(row[xpos])==0){
wchar_t word[] = {L"%d\", "};
int i = 0;
while(word[i]!='\0')
putwchar(word[i++]);
putwchar(row[xpos]);
}
else{
xpos++;
while(row[xpos+1]!=')'){
if(it_is_what(row[xpos])==11)
putwchar('\\');
if(it_is_what(row[xpos])==12)
putwchar('%');
putwchar(row[xpos]);
xpos++;
}
putwchar('\"');
}
}
{ // PRINT POST LETTERS
wchar_t word[] = {L");\n"};
int i = 0;
while(word[i]!='\0')putwchar(word[i++]);
}
break;
}// printf(L"letters");
}
{ // ERROR HANDLE
if (command == 0 && row[0] != WEOF){
if(row[rowCursor]=='\n')row[rowCursor]='\0';
wchar_t err[] = L"ERROR CMD NOT FOUND!";
int k = 0;
while(err[k++]!='\0')putwchar(err[k-1]);
return 1;
}
}
}while(row[0] != WEOF && deathMark);
return 0;
}
int it_is_what(wchar_t ch){
if(ch>='a'&&ch<='z')return 0;
if(ch>='A'&&ch<='Z')return 1;
if(ch>='0'&&ch<='9')return 2;
if(ch == '=' || ch == '>' || ch == '<' || ch == '!')return 8;
if(ch == '*' || ch == '-' || ch == '+' || ch == '/')return 9;
if(ch == '\\' || ch == '\"' || ch == '\'')return 11;
if(ch == '%')return 12;
return -1;
}
+373
View File
@@ -0,0 +1,373 @@
#include <stdio.h>
#include <wchar.h>
#include <locale.h>
#define MAXINPUTARRAY 1000
#define MAXKNOWN 30
#define MAXKNOWNSYMB 32
#define MAXROW 80
#define CMDLIST 4
// --- GLOBAL DATA ---
wchar_t G_knownint[MAXKNOWN][MAXKNOWNSYMB] = {0};
int G_knownCount = 0;
// --- FUNCTION DECLARATIONS ---
int it_is_what(wchar_t ch);
int are_strings_equal(const wchar_t *s1, const wchar_t *s2);
int is_variable_known(const wchar_t *name);
void put_wchar_string(const wchar_t *s);
void put_char_string(const char *s);
// --- MAIN TRANSLATOR LOGIC ---
int main() {
setlocale(LC_ALL, "");
wchar_t massive[MAXINPUTARRAY] = {0};
int CellsInMainArray = 0;
{ // GET INPUT
wchar_t ch;
while ((ch = getwchar()) != WEOF) {
if (CellsInMainArray >= MAXINPUTARRAY) { return 1001; }
massive[CellsInMainArray++] = ch;
}
}
{ // PRE-SCAN: DECLARE ALL VARIABLES AS INT
put_char_string("#include <stdio.h>\n");
put_char_string("int main(){\n");
int k = 0;
while (k < CellsInMainArray) {
if (it_is_what(massive[k]) == 0 || it_is_what(massive[k]) == 1) {
wchar_t tempName[MAXKNOWNSYMB] = {0};
int len = 0;
int startK = k;
{ // EXTRACT NAME
while (startK < CellsInMainArray && (it_is_what(massive[startK]) >= 0)) {
if (len < MAXKNOWNSYMB - 1) tempName[len++] = massive[startK];
startK++;
}
}
{ // CHECK KEYWORDS AND DECLARE
int isKeyword = 0;
if (are_strings_equal(tempName, L"if") || are_strings_equal(tempName, L"while") ||
are_strings_equal(tempName, L"for") || are_strings_equal(tempName, L"print") ||
are_strings_equal(tempName, L"in") || are_strings_equal(tempName, L"range") ||
are_strings_equal(tempName, L"int") || are_strings_equal(tempName, L"input")) isKeyword = 1;
if (!isKeyword && tempName[0] != L'\0') {
if (!is_variable_known(tempName) && G_knownCount < MAXKNOWN) {
for (int c = 0; c < len; c++) G_knownint[G_knownCount][c] = tempName[c];
G_knownCount++;
// DECLARE VARIABLE
put_char_string("int ");
put_wchar_string(tempName);
put_char_string(" = 0;\n");
}
}
}
k = startK;
} else {
k++;
}
}
putwchar(L'\n');
}
// --- SECOND PASS: LEXICAL ANALYSIS AND TRANSLATION ---
int massiveCursor = 0;
wchar_t row[MAXROW] = {0};
int deathMark = 1;
int blockLevel = 0;
do {
if (massiveCursor >= CellsInMainArray) break;
int command = 0;
int rowCursor = 0;
int initialSpaceCount = 0;
{ // GET ROW AND INDENTATION
for (int i = 0; i < MAXROW; i++) row[i] = 0;
rowCursor = 0;
while (massiveCursor < CellsInMainArray && rowCursor < MAXROW - 1) {
wchar_t cur = massive[massiveCursor];
if (cur == L'\n') { massiveCursor++; break; }
if (cur == WEOF || massiveCursor == CellsInMainArray - 1) { deathMark = 0; }
row[rowCursor++] = cur;
massiveCursor++;
}
int i = 0;
while (row[i] == L' ' || row[i] == L'\t') { initialSpaceCount++; i++; }
// CLOSE BLOCK
if (blockLevel == 1 && initialSpaceCount == 0 && rowCursor > 0) {
put_char_string("}\n");
blockLevel = 0;
}
// PRINT INDENTATION
for (int j = 0; j < initialSpaceCount; j++) putwchar(L' ');
// TRIM ROW
if (initialSpaceCount > 0) {
for (int j = 0; j < rowCursor - initialSpaceCount; j++) {
row[j] = row[j + initialSpaceCount];
}
rowCursor -= initialSpaceCount;
for (int j = rowCursor; j < MAXROW; j++) row[j] = 0;
}
}
{ // HANDLE PYTHON COMMENTS (#)
int hashPos = -1;
for (int i = 0; i < rowCursor; i++) {
if (row[i] == L'#') { hashPos = i; break; }
}
if (hashPos != -1) {
put_char_string("//");
for (int k = 0; k < rowCursor; k++) {
if (row[k] == L'#') break;
putwchar(row[k]);
}
for (int k = hashPos + 1; k < rowCursor; k++) putwchar(row[k]);
putwchar(L'\n');
continue;
}
}
// SKIP EMPTY LINES
if (rowCursor == 0) {
putwchar(L'\n');
continue;
}
{ // DETERMINE COMMAND TYPE
wchar_t cmd_list[CMDLIST][10] = {L"if", L"while", L"for", L"print"};
for (int i = 0; i < CMDLIST; i++) {
int lenCmd = 0;
while (cmd_list[i][lenCmd] != L'\0') lenCmd++;
if (rowCursor >= lenCmd) {
int match = 1;
for (int k = 0; k < lenCmd; k++) {
if (row[k] != cmd_list[i][k]) { match = 0; break; }
}
if (match) {
int pos = lenCmd;
while(row[pos] == L' ') pos++;
if (i == 3) { // PRINT
if (row[pos] == L'(') { command = 4; break; }
} else { // IF, WHILE, FOR
int colonPos = -1;
for (int p = pos; p < rowCursor; p++) {
if (row[p] == L':') { colonPos = p; break; }
}
if (colonPos != -1) { command = i + 1; break; }
}
}
}
}
}
{ // HANDLE ASSIGNMENT / OPERATION (command == 0)
if (command == 0) {
int eqPos = -1;
int plusEqPos = -1;
int varNameEnd = -1;
for (int i = 0; i < rowCursor; i++) {
if (row[i] == L'=') {
eqPos = i;
if (i > 0 && row[i - 1] == L'+') plusEqPos = i;
varNameEnd = i - 1;
while(varNameEnd >= 0 && row[varNameEnd] == L' ') varNameEnd--;
break;
}
}
// If assignment found and not comparison
if (eqPos > 0 && row[eqPos + 1] != L'=' && plusEqPos == -1) {
// 1. Check for input pattern
wchar_t inputPattern[] = L"int(input())";
int isInput = 1;
int checkIdx = 0;
int valPos = eqPos + 1;
while (row[valPos] == L' ') valPos++;
while (inputPattern[checkIdx] != L'\0') {
if (row[valPos + checkIdx] != inputPattern[checkIdx]) { isInput = 0; break; }
checkIdx++;
}
if (isInput) {
// INPUT (scanf)
put_char_string("scanf(\"%d\", &");
for (int j = 0; j <= varNameEnd; j++) putwchar(row[j]);
put_char_string(");\n");
} else {
// REGULAR ASSIGNMENT (x = -5, x = a + 1)
for (int i = 0; i < rowCursor; i++) { putwchar(row[i]); }
put_char_string(";\n");
}
continue;
}
// Augmented Assignment (x += 1) or other unknown lines
for (int i = 0; i < rowCursor; i++) { putwchar(row[i]); }
put_char_string(";\n");
continue;
}
}
{ // TRANSLATE COMMAND (switch)
switch (command) {
case 1: // IF
case 2: // WHILE
case 3: { // FOR
wchar_t *start_word;
int len_cmd;
if (command == 1) { start_word = L"if("; len_cmd = 2; }
else if (command == 2) { start_word = L"while("; len_cmd = 5; }
else { start_word = L"for("; len_cmd = 3; }
put_wchar_string(start_word);
int pos = len_cmd;
while (row[pos] == L' ') pos++;
if (command == 3) { // FOR (i in range(10))
wchar_t iterVar[MAXKNOWNSYMB] = {0};
int ivLen = 0;
// GET ITERATOR NAME
while (row[pos] != L' ' && row[pos] != L'\0' && pos < rowCursor && row[pos] != L':') {
iterVar[ivLen++] = row[pos];
pos++;
}
// SKIP 'in range'
while (pos < rowCursor && row[pos] != L'(') pos++;
pos++;
// C FORMAT: for(i = 0; i < limit; i++)
put_wchar_string(iterVar); put_char_string(" = 0;");
put_wchar_string(iterVar); put_char_string(" < ");
// GET LIMIT
while (pos < rowCursor && row[pos] != L')' && row[pos] != L':') { putwchar(row[pos++]); }
put_char_string(";");
put_wchar_string(iterVar); put_char_string("++");
} else {
// IF / WHILE CONDITION (Handling x >= y conditions)
while (pos < rowCursor && row[pos] != L':') {
if (row[pos] == L'>' && row[pos+1] == L'=') {
put_char_string(" >= ");
pos += 2;
} else if (row[pos] == L'<' && row[pos+1] == L'=') {
put_char_string(" <= ");
pos += 2;
} else if (row[pos] == L'!' && row[pos+1] == L'=') {
put_char_string(" != ");
pos += 2;
} else if (row[pos] == L'=' && row[pos+1] == L'=') {
put_char_string(" == ");
pos += 2;
} else {
putwchar(row[pos++]);
}
}
}
put_char_string(")\n");
// OPEN BLOCK
put_char_string("{\n");
blockLevel = 1;
break;
}
case 4: { // PRINT (print(x) or print("hello"))
put_char_string("printf(");
int pos = 5;
while (row[pos] != L'(') pos++;
pos++;
int isString = (row[pos] == L'\"');
if (isString) {
putwchar(L'\"');
pos++;
while (pos < rowCursor && row[pos] != L')') {
if (row[pos] == L'\"' && isString) break;
putwchar(row[pos++]);
}
putwchar(L'\"');
} else {
put_char_string("\"%d\", ");
while (pos < rowCursor && row[pos] != L')') {
putwchar(row[pos++]);
}
}
put_char_string(");\n");
break;
}
}
}
} while (deathMark);
{ // FINAL BRACKETS
if (blockLevel == 1) {
put_char_string("}\n");
}
put_char_string("}\n");
}
return 0;
}
// --- AUXILIARY FUNCTION DEFINITIONS ---
void put_wchar_string(const wchar_t *s) {
int i = 0;
while (s[i] != L'\0') { putwchar(s[i++]); }
}
void put_char_string(const char *s) {
int i = 0;
while (s[i] != '\0') { putwchar(s[i++]); }
}
int it_is_what(wchar_t ch) {
if (ch >= L'a' && ch <= L'z') return 0;
if (ch >= L'A' && ch <= L'Z') return 1;
if (ch >= L'0' && ch <= L'9') return 2;
if (ch == L'_') return 3;
return -1;
}
int are_strings_equal(const wchar_t *s1, const wchar_t *s2) {
int i = 0;
while (s1[i] != L'\0' || s2[i] != L'\0') {
if (s1[i] != s2[i]) return 0;
i++;
}
return 1;
}
int is_variable_known(const wchar_t *name) {
if (name[0] == L'\0') return 1;
for (int r = 0; r < G_knownCount; r++) {
if (are_strings_equal(G_knownint[r], name)) {
return 1;
}
}
return 0;
}
Binary file not shown.
+43
View File
@@ -0,0 +1,43 @@
#include <stdio.h>
int main(){
int global_var = 0;
int neg_num = 0;
int result = 0;
int user_age = 0;
int Negatine = 0;
int num = 0;
int n = 0;
int counter = 0;
int i = 0;
global_var = 10 ;
neg_num = -5 ;
result = global_var + neg_num ;
scanf("%d", &user_age);
if(global_var >= 5)
{
result = result + 1;
}
if(neg_num <= 0)
{
printf("Negatine num\n");
}
counter = 0;
while(counter <= 3)
{
printf("%d", counter);
counter += 1;
}
for(i = 0;i < 10;i++)
{
result = result + 1 ;
}
printf("%d", result);
printf("%d", user_age);
}
Binary file not shown.
+5
View File
@@ -0,0 +1,5 @@
gcc ./main.c -o ./output/prog
./output/prog < ./input/test.py > output/output.c
bat ./output/output.c
gcc ./output/output.c -o ./output/output
./output/output < ./input/test.num