I want to create a program that checks if the input is syntactically valid in C -


how create c program takes in command in c input, , prints if there errors?

for example,

    input: for(i=0; i<5; i++);     no errors.      input: for((i=0); i>2,(i<5) ; i++);     no errors.      input: for(i=0, i<5; i++);     error.      input: for((i=0; i<5; i++));     error. 

i think shortest way compile input string, , check if errors occur. don't know how compile piece of code passed during runtime. also, there problem of undeclared variables.

c particuraly complicated parse. if remove pre-processor side of it, there still tricky parts.

if learning yourself, can c grammar (there in lex/yacc format ansi c) can at.

from example guess want able recognize subset of c, not entire language, correct? if case, should define subset , write parser it.

rather trying write parser hand, should learn grammars , parser generators if haven't worked them already.

if it's subset of c you're interested in, use peg parse generator packcc parser.

as super-simple example, following parser:

%prefix "mc"  stmt <- _ assign            { printf("assignment\n"); }         / _ if                 { printf("if\n"); }      / ( !eol . )* eol      { printf("error\n"); }  if <- 'if' _ '(' _ var _ ')' _ stmt   assign <- var _ '=' _ num _ ';' _ eol var    <- [a-za-z_] [0-9a-za-z_]* num    <- [0-9]+ _      <- [ \t]* eol    <- '\n' / '\r\n' / '\r'  %% int main() {     mc_context_t *ctx = mc_create(null);     while (mc_parse(ctx, null));     mc_destroy(ctx);     return 0; } 

will accept assignment (where lvalue variable name , rvalue integer) , if statements condition variable name. assuming parser in file mu.peg

home> packcc mu.peg home> gcc -o mu mu.c home> ./mu t = 5; assignment t = 5 error if (x) p = 3; assignment if if (x) if (y) t = 3; assignment if  if 

if, instead, need check sintatically valid c code @ runtime , there's compiler installed on system, tipically gcc or clang, can call via system() , intercept error. depending on type of checks want on code, can consider using static analyzer splint.

if need embed in application, can try tcc availble library.


Popular posts from this blog