C
Compiler component
Write a small language with lexer and parser.
Compiler component
In the third lesson you add the compiler component. The parse_command function takes a command string and returns a code if it recognizes it. This is a simplified combination of a compiler's lexer and parser steps.
A real compiler first splits source code into tokens, then produces an abstract syntax tree (AST). Here we compare the command string with strcmp and return an integer: 1 for "help", 2 for "exit", 0 for unknown. This is the basis of command-driven interfaces. The previous lesson's solution is in the starting code.
Command recognition with strcmp
The strcmp(a, b) function compares two strings: it returns 0 if equal. For command recognition: if (strcmp(cmd, "help") == 0) return 1;. This pattern is the basis of command-driven interfaces.
For multiple commands, a chain of if statements is written: each command is checked with a separate strcmp. If no match, a default return (0) is given. This resembles a compiler's keyword recognition step. The string.h header provides strcmp. The parse_command result is used in main; for example, a switch processes different commands.
Exercise Add the parse_command function
Below the existing definitions, write int parse_command(const char *cmd). If strcmp(cmd, "help") == 0 return 1;, if strcmp(cmd, "exit") == 0 return 2;, else return 0;. In main call printf("Komut: %d\n", parse_command("help")).
Show example solution
#include <stdio.h>
#include <string.h>
void kernel_init(void);
int parse_command(const char *cmd);
int security_check(const char *buf, int len);
void kernel_init(void) {
printf("Çekirdek başladı\n");
}
int syscall(int num) {
return num * 2;
}
int parse_command(const char *cmd) {
if (strcmp(cmd, "help") == 0) return 1;
if (strcmp(cmd, "exit") == 0) return 2;
return 0;
}
int main(void) {
printf("Proje başladı\n");
kernel_init();
printf("Komut: %d\n", parse_command("help"));
return 0;
}
Test yourself
-
Match parser concept
- strcmp
- String compare
- parse_command
- Command recognition
- "help"
- Return 1
- "exit"
- Return 2
-
Complete the strcmp call
if (strcmp(cmd, ____) == 0) return 1;
Show answer
if (strcmp(cmd, "help") == 0) return 1;
-
What does parse_command("help") return?
Show answer
1 — parse_command returns 1 for "help".
Next lesson: Security layer