Compiler practice three syntax parser for arithmetic expressions

Source: Internet
Author: User

Part of the code from MOOC


#include <ctype.h> #include <stdio.h> #include <stdlib.h>void parse_f (); void parse_t (); void Parse_e ( ); void error (char *want, Char got); int I;char *str = 0;void error (char *want, Char got) {fprintf (stderr, "compling thi  S expression:\n%s\n ", str);  int j = i;  while (j--) fprintf (stderr, "");  fprintf (stderr, "^\n"); fprintf (stderr, "Syntax error at position:%d\n" "\texpecting:%s\n" "\tbut Got:%c\n", I  , want, got);  Exit (0); return;}  void Parse_f () {char c = str[i];    if (IsDigit (c)) {i++;  Return    } if (c== ' (') {i++;    Parse_e ();    c = Str[i];      if (c== ') ') {i++;    Return    } error ("\ ') \ '", c);  Return  } error ("\ ' 0-9\ ' or \ ' (\ '", c); return;}  void parse_t () {parse_f ();  char C = str[i];    while (c== ' * ' | | c = = '/') {i++;    Parse_f ();  c = Str[i]; } return;  void Parse_e () {parse_t ();  char C = str[i];    while (c== ' + ' | | c = = '-') {i++;    parse_t ();  c = Str[i]; } return; void PArse (char *e) {str = e;  i = 0;  Parse_e ();  if (str[i]== ') return;  Error ("\ ' +\ ' or ' \\0\ '", Str[i]); return;} Your job://Add Some code into the function parse_e () and//parse_t to P Arse "-" and "/" correctly.//when you finish your tasks, NO error message//should be generated.//enjoy! :-P int Main (char argc, char **argv) {//There is the following rules on an expression://1.  Every expression is represented as a string; 2.  integers is non-negative; 3.  Integers is between 0-9.  Char *e;  E = "(2)";  Parse (e);  E = "(3+4*5))";  Parse (e);  E = "(8-2) * *";  Parse (e);  E = "(8-2)/3";    Parse (e); return 0;}

with June

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Compiler practice three syntax parser for arithmetic expressions

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.