Для студентов МГУ им. Ломоносова по предмету Практикум (Прикладное программное обеспечение и системы программирования)C grammar analyzerC grammar analyzer 2019-05-09СтудИзба

Другое: C grammar analyzer

Описание

Описание файла отсутствует

Характеристики учебной работы

Учебное заведение
Семестр
Просмотров
70
Скачиваний
2
Размер
271,61 Kb

Список файлов

  • C grammar analyzer
  • C optimizator (not finished (only started))
  • C_grammar_analyser 54,59 Kb
  • C_grammar_lex.txt 25,4 Kb
  • C_grammar_yacc.c 115,17 Kb
  • C_grammar_yacc.h 4,94 Kb
  • C_grammar_yacc.output 337,69 Kb
  • C_grammar_yacc.txt 18,01 Kb
  • lex.yy.c 79,87 Kb
  • lex.yy.o 25,72 Kb
  • makeit.t 601 b
  • try it 72 b
  • C optimizator (not finished)
  • C_grammar_analyser 71,22 Kb
  • C_grammar_lex.txt 43,36 Kb
  • C_grammar_yacc.c 168,38 Kb
  • C_grammar_yacc.h 4,94 Kb
  • C_grammar_yacc.output 330,33 Kb
  • C_grammar_yacc.txt 59,15 Kb
  • input.txt 114 b
  • lex.yy.c 97,66 Kb
  • lex.yy.o 30,34 Kb
  • makeit.t 601 b
  • output.txt 141 b
  • test_new_tech.cpp 1,29 Kb
  • workspace 95 b
  • Only C grammar analyser
  • C_grammar_analyser 50,04 Kb
  • C_grammar_lex.txt 25,21 Kb
  • C_grammar_yacc.c 110,87 Kb
  • C_grammar_yacc.h 4,8 Kb
  • C_grammar_yacc.output 330,33 Kb
  • C_grammar_yacc.txt 14,86 Kb
  • lex.yy.c 79,67 Kb
  • lex.yy.o 23,35 Kb
  • makeit.t 601 b
  • try it 72 b
  • Прочти меня!!!.txt 136 b
C_grammar_lex

%e 1019

%p 2807

%n 371

%k 284

%a 1213

%o 1117

%{

/*====================================== ======================================== ==========================SETS========== =========================*/

%}

O [0-7]

D [0-9]

NZ [1-9]

L [a-zA-Z_]

A [a-zA-Z_0-9]

H [a-fA-F0-9]

HP (0[xX])

E ([Ee][+-]?{D}+)

P ([Pp][+-]?{D}+)

FS (f|F|l|L)

IS (((u|U)(l|L|ll|LL)?)|((l|L|ll|LL)(u|U)?) )

CP (u|U|L)

SP (u8|u|U|L)

ES (\\(['"\?\\abfnrtv]|[0-7]{1,3}|x[a-fA-F0 -9]+))

WS [ \t\v\n\f]

%{

/*====================================== ======================================== ==========================C=DECLARATIONS =========================*/

%}

%{

/*====================================== =================================SYSTEM= SETTINGS===============*/

/*#include "y.tab.h"*/ /* For compilation using C */

#include "C_grammar_yacc.h" /* For compilation using C++ */

extern YYSTYPE yylval;

extern void yyerror(const char *); /* prints grammar violation message */

extern int sym_type(const char *); /* returns type from symbol table */

#define sym_type(identifier) IDENTIFIER /* with no symbol table, fake it */

static void comment(void);

static int check_type(void);

#define YYSTYPE char*

/*====================================== =================================PROGRAM =SETINGS===============*/

#include <stdio.h>

extern int doing_output; /* This parameter is set to 1 if we should write current strings in output

and is set to 0 if we are not going to do print anything */

#define TOKEN_OUTPUT \

{ \

if (doing_output == 1) \

printf ("%s", yytext); \

};

%}

%%

%{

/*====================================== ======================================== ==========================COMMENTS====== =========================*/

%}

"/*" { comment(); }

"//".* { /* consume //-comment */ }

%{

/*====================================== ======================================== ==========================KEY=WORDS===== =========================*/

%}

"auto" {

TOKEN_OUTPUT;

return(AUTO);

}

"break" {

TOKEN_OUTPUT;

return(BREAK);

}

"case" {

TOKEN_OUTPUT;

return(CASE);

}

"char" {

TOKEN_OUTPUT;

return(CHAR);

}

"const" {

TOKEN_OUTPUT;

return(CONST);

}

"continue" {

TOKEN_OUTPUT;

return(CONTINUE);

}

"default" {

TOKEN_OUTPUT;

return(DEFAULT);

}

"do" {

TOKEN_OUTPUT;

return(DO);

}

"double" {

TOKEN_OUTPUT;

return(DOUBLE);

}

"else" {

TOKEN_OUTPUT;

return(ELSE);

}

"enum" {

TOKEN_OUTPUT;

return(ENUM);

}

"extern" {

TOKEN_OUTPUT;

return(EXTERN);

}

"float" {

TOKEN_OUTPUT;

return(FLOAT);

}

"for" {

TOKEN_OUTPUT;

return(FOR);

}

"goto" {

TOKEN_OUTPUT;

return(GOTO);

}

"if" {

TOKEN_OUTPUT;

return(IF);

}

"inline" {

TOKEN_OUTPUT;

return(INLINE);

}

"int" {

TOKEN_OUTPUT;

return(INT);

}

"long" {

TOKEN_OUTPUT;

return(LONG);

}

"register" {

TOKEN_OUTPUT;

return(REGISTER);

}

"restrict" {

TOKEN_OUTPUT;

return(RESTRICT);

}

"return" {

TOKEN_OUTPUT;

return(RETURN);

}

"short" {

TOKEN_OUTPUT;

return(SHORT);

}

"signed" {

TOKEN_OUTPUT;

return(SIGNED);

}

"sizeof" {

TOKEN_OUTPUT;

return(SIZEOF);

}

"static" {

TOKEN_OUTPUT;

return(STATIC);

}

"struct" {

TOKEN_OUTPUT;

return(STRUCT);

C_grammar_yacc

%union

{

char* str;

}

%token <str> IDENTIFIER

%token <str> I_CONSTANT

%token <str> F_CONSTANT

%token STRING_LITERAL FUNC_NAME SIZEOF

%token PTR_OP INC_OP DEC_OP LEFT_OP RIGHT_OP LE_OP GE_OP EQ_OP NE_OP

%token AND_OP OR_OP MUL_ASSIGN DIV_ASSIGN MOD_ASSIGN ADD_ASSIGN

%token SUB_ASSIGN LEFT_ASSIGN RIGHT_ASSIGN AND_ASSIGN

%token XOR_ASSIGN OR_ASSIGN

%token TYPEDEF_NAME ENUMERATION_CONSTANT

%token TYPEDEF EXTERN STATIC AUTO REGISTER INLINE

%token CONST RESTRICT VOLATILE

%token BOOL CHAR SHORT INT LONG SIGNED UNSIGNED FLOAT DOUBLE VOID

%token COMPLEX IMAGINARY

%token STRUCT UNION ENUM ELLIPSIS

%token CASE DEFAULT IF ELSE SWITCH WHILE DO FOR GOTO CONTINUE BREAK RETURN

%token ALIGNAS ALIGNOF ATOMIC GENERIC NORETURN STATIC_ASSERT THREAD_LOCAL

%start translation_unit

%type <str> constant

%type <str> primary_expression

%type <str> postfix_expression

%type <str> unary_expression

%type <str> cast_expression

%type <str> multiplicative_expression

%type <str> additive_expression

%type <str> shift_expression

%type <str> relational_expression

%type <str> equality_expression

%type <str> and_expression

%type <str> exclusive_or_expression

%type <str> inclusive_or_expression

%type <str> logical_and_expression

%type <str> logical_or_expression

%type <str> conditional_expression

%type <str> assignment_expression

%type <str> expression

%type <str> selection_statement

%type <str> enumeration_constant

%{

/*====================================== =================================SYSTEM= SETTINGS===============*/

/* For compilation using C++ */

extern "C"

{

int yyparse(void);

int yylex(void);

int yywrap(void);

void yyerror(const char *);

/*int yydebug;*/

}

/*====================================== =================================PROGRAM =SETTINGS==============*/

#include <iostream>

#include <string.h>

#include <stdlib.h>

#include <errno.h>

using std::cout;

using std::cerr;

extern "C"

{

int doing_output = 1; /* This parameter is set to 1 if we should write current strings in output

and is set to 0 if we are not going to do it (for example, if we have "if (0) {...}") */

/* In here it will be very often seen how I am saving current doing_output into $$

and after (within single non-terminal rule) restoring it back */

}

%}

%%

/*====================================== ======================================== ======================================== ===C=GRAMMAR===================*/

primary_expression

: IDENTIFIER

| constant

{ $$ = $1; }

| string

| '(' expression ')'

| generic_selection

;

constant

: I_CONSTANT /* includes character_constant */

{ $$ = $1; }

| F_CONSTANT

| ENUMERATION_CONSTANT /* after it has been defined as such */

;

enumeration_constant /* before it has been defined as such */

: IDENTIFIER

;

string

: STRING_LITERAL

| FUNC_NAME

;

generic_selection

: GENERIC '(' assignment_expression ',' generic_assoc_list ')'

;

generic_assoc_list

: generic_association

| generic_assoc_list ',' generic_association

;

generic_association

: type_name ':' assignment_expression

| DEFAULT ':' assignment_expression

;

postfix_expression

: primary_expression

{ $$ = $1; }

| postfix_expression '[' expression ']'

| postfix_expression '(' ')'

| postfix_expression '(' argument_expression_list ')'

| postfix_expression '.' IDENTIFIER

| postfix_expression PTR_OP IDENTIFIER

| postfix_expression INC_OP

| postfix_expression DEC_OP

| '(' type_name ')' '{' initializer_list '}'

| '(' type_name ')' '{' initializer_list ',' '}'

;

argument_expression_list

: assignment_expression

| argument_expression_list ',' assignment_expression

;

unary_expression

: postfix_expression

{ $$ = $1; }

| INC_OP unary_expression

| DEC_OP unary_expression

| unary_operator cast_expression

| SIZEOF unary_expression

| SIZEOF '(' type_name ')'

| ALIGNOF '(' type_name ')'

;

unary_operator

: '&'

| '*'

| '+'

| '-'

| '~'

| '!'

;

cast_expression

: unary_expression

{ $$ = $1; }

| '(' type_name ')' cast_expression

;

multiplicative_expression

: cast_expression

{ $$ = $1; }

| multiplicative_expression '*' cast_expression

| multiplicative_expression '/' cast_expression

| multiplicative_expression '%' cast_expression

;

additive_expression

: multiplicative_expression

{ $$ = $1; }

| additive_expression '+' multiplicative_expression

| additive_expression '-' multiplicative_expression

;

shift_expression

: additive_expression

{ $$ = $1; }

| shift_expression LEFT_OP additive_expression

| shift_expression RIGHT_OP additive_expression

;

relational_expression

: shift_expression

{ $$ = $1; }

| relational_expression '<' shift_expression

| relational_expression '>' shift_expression

| relational_expression LE_OP shift_expression

| relational_expression GE_OP shift_expression

;

equality_expression

: relational_expression

{ $$ = $1; }

| equality_expression EQ_OP relational_expression

| equality_expression NE_OP relational_expression

;

and_expression

: equality_expression

{ $$ = $1; }

| and_expression '&' equality_expression

;

exclusive_or_expression

: and_expression

{ $$ = $1; }

| exclusive_or_expression '^' and_expression

;

inclusive_or_expression

: exclusive_or_expression

{ $$ = $1; }

| inclusive_or_expression '|' exclusive_or_expression

;

logical_and_expression

: inclusive_or_expression

{ $$ = $1; }

| logical_and_expression AND_OP inclusive_or_expression

;

logical_or_expression

C_grammar_lex

/*====================================== ======================================== ==========================SETTINGS====== =========================*/

%e 1019

%p 2807

%n 371

%k 284

%a 1213

%o 1117

%{

/*====================================== ======================================== ==========================SETS========== =========================*/

%}

O [0-7]

D [0-9]

NZ [1-9]

L [a-zA-Z_]

A [a-zA-Z_0-9]

H [a-fA-F0-9]

HP (0[xX])

E ([Ee][+-]?{D}+)

P ([Pp][+-]?{D}+)

FS (f|F|l|L)

IS (((u|U)(l|L|ll|LL)?)|((l|L|ll|LL)(u|U)?) )

CP (u|U|L)

SP (u8|u|U|L)

ES (\\(['"\?\\abfnrtv]|[0-7]{1,3}|x[a-fA-F0 -9]+))

WS [ \t\v\n\f]

%{

/*====================================== ======================================== ==========================C=DECLARATIONS =========================*/

%}

%{

/*====================================== =================================SYSTEM= SETTINGS===============*/

/*#include "y.tab.h"*/ /* For compilation using C */

#include "C_grammar_yacc.h" /* For compilation using C++ */

extern void yyerror(const char *); /* prints grammar violation message */

extern int sym_type(const char *); /* returns type from symbol table */

/*====================================== =================================LEX=YAC C=SETTINGS=============*/

extern YYSTYPE yylval;

#define YYSTYPE char*

#define sym_type(identifier) IDENTIFIER /* with no symbol table, fake it */

static void comment(void);

static int check_type(void);

/*====================================== =================================PROGRAM =SETINGS===============*/

#include <stdio.h>

#include <string.h>

int _indentation = 0; /* This constant is for looking after style, after every "\n" we must place spaces */

void indentationInsertBefore (const int indentation);

void indentationInsertAfter (const int indentation);

void spaceInsertAfter ();

%}

%{

/*====================================== ======================================== ======================================== ======================================== ======================================== =*/

/*====================================== ======================================== ======================================== ======================================== ======================================== =*/

/*====================================== ======================================== ======================================== ======================================== ======================================== =*/

%}

%%

%{

/*====================================== ======================================== ================COMMENTS================ ===============*/

%}

"/*" { comment(); }

"//".* { /* consume //-comment */ }

%{

/*====================================== ======================================== ================KEY=WORDS=============== ===============*/

%}

"auto" {

yylval.str = strdup (yytext);

spaceInsertAfter ();

printf ("%s", yytext);

return(AUTO);

}

"break" {

yylval.str = strdup (yytext);

spaceInsertAfter ();

printf ("%s", yytext);

return(BREAK);

}

"case" {

yylval.str = strdup (yytext);

spaceInsertAfter ();

printf ("%s", yytext);

return(CASE);

}

"char" {

yylval.str = strdup (yytext);

spaceInsertAfter ();

printf ("%s", yytext);

return(CHAR);

}

"const" {

yylval.str = strdup (yytext);

spaceInsertAfter ();

printf ("%s", yytext);

return(CONST);

}

"continue" {

yylval.str = strdup (yytext);

spaceInsertAfter ();

printf ("%s", yytext);

return(CONTINUE);

}

"default" {

yylval.str = strdup (yytext);

spaceInsertAfter ();

printf ("%s", yytext);

return(DEFAULT);

}

"do" {

yylval.str = strdup (yytext);

spaceInsertAfter ();

printf ("%s", yytext);

return(DO);

}

"double" {

yylval.str = strdup (yytext);

spaceInsertAfter ();

printf ("%s", yytext);

return(DOUBLE);

}

"else" {

yylval.str = strdup (yytext);

spaceInsertAfter ();

printf ("%s", yytext);

return(ELSE);

}

"enum" {

yylval.str = strdup (yytext);

spaceInsertAfter ();

printf ("%s", yytext);

return(ENUM);

}

"extern" {

yylval.str = strdup (yytext);

spaceInsertAfter ();

printf ("%s", yytext);

return(EXTERN);

}

"float" {

yylval.str = strdup (yytext);

spaceInsertAfter ();

printf ("%s", yytext);

return(FLOAT);

C_grammar_yacc

/*====================================== ======================================== ======================================== ===UNION=======================*/

%union

{

char* str;

}

/*====================================== ======================================== ======================================== ===TOKENS======================*/

%token <str> IDENTIFIER I_CONSTANT F_CONSTANT STRING_LITERAL FUNC_NAME SIZEOF

%token <str> PTR_OP INC_OP DEC_OP LEFT_OP RIGHT_OP LE_OP GE_OP EQ_OP NE_OP

%token <str> AND_OP OR_OP MUL_ASSIGN DIV_ASSIGN MOD_ASSIGN ADD_ASSIGN

%token <str> SUB_ASSIGN LEFT_ASSIGN RIGHT_ASSIGN AND_ASSIGN

%token <str> XOR_ASSIGN OR_ASSIGN

%token <str> TYPEDEF_NAME ENUMERATION_CONSTANT

%token <str> TYPEDEF EXTERN STATIC AUTO REGISTER INLINE

%token <str> CONST RESTRICT VOLATILE

%token <str> BOOL CHAR SHORT INT LONG SIGNED UNSIGNED FLOAT DOUBLE VOID

%token <str> COMPLEX IMAGINARY

%token <str> STRUCT UNION ENUM ELLIPSIS

%token <str> CASE DEFAULT IF ELSE SWITCH WHILE DO FOR GOTO CONTINUE BREAK RETURN

%token <str> ALIGNAS ALIGNOF ATOMIC GENERIC NORETURN STATIC_ASSERT THREAD_LOCAL

%token <str> ';' '{' '}' ',' ':' '=' '(' ')' '[' ']' '.' '&' '!' '~' '-' '+' '*' '/' '%' '<' '>' '^' '|' '?'

/*====================================== ======================================== ======================================== ===TYPES=======================*/

%type <str> primary_expression

%type <str> constant

%type <str> enumeration_constant

%type <str> string

%type <str> generic_selection

%type <str> generic_assoc_list

%type <str> generic_association

%type <str> postfix_expression

%type <str> argument_expression_list

%type <str> unary_expression

%type <str> unary_operator

%type <str> cast_expression

%type <str> multiplicative_expression

%type <str> additive_expression

%type <str> shift_expression

%type <str> relational_expression

%type <str> equality_expression

%type <str> and_expression

%type <str> exclusive_or_expression

%type <str> inclusive_or_expression

%type <str> logical_and_expression

%type <str> logical_or_expression

%type <str> conditional_expression

%type <str> assignment_expression

%type <str> assignment_operator

%type <str> expression

%type <str> constant_expression

%type <str> declaration

%type <str> declaration_specifiers

%type <str> init_declarator_list

%type <str> init_declarator

%type <str> storage_class_specifier

%type <str> type_specifier

%type <str> struct_or_union_specifier

%type <str> struct_or_union

%type <str> struct_declaration_list

%type <str> struct_declaration

%type <str> specifier_qualifier_list

%type <str> struct_declarator_list

%type <str> struct_declarator

%type <str> enum_specifier

%type <str> enumerator_list

%type <str> enumerator

%type <str> atomic_type_specifier

%type <str> type_qualifier

%type <str> function_specifier

%type <str> alignment_specifier

%type <str> declarator

%type <str> direct_declarator

%type <str> pointer

%type <str> type_qualifier_list

%type <str> parameter_type_list

%type <str> parameter_list

%type <str> parameter_declaration

%type <str> identifier_list

%type <str> type_name

%type <str> abstract_declarator

%type <str> direct_abstract_declarator

%type <str> initializer

%type <str> initializer_list

%type <str> designation

%type <str> designator_list

%type <str> designator

%type <str> static_assert_declaration

%type <str> statement

%type <str> labeled_statement

%type <str> compound_statement

%type <str> block_item_list

%type <str> block_item

%type <str> expression_statement

%type <str> selection_statement

%type <str> iteration_statement

%type <str> jump_statement

%type <str> translation_unit

%type <str> external_declaration

%type <str> function_definition

%type <str> declaration_list

/*====================================== ======================================== ======================================== ===START=DECLARATION===========*/

%start translation_unit

%{

/*====================================== =================================SYSTEM= SETTINGS===============*/

/* For compilation using C++ */

extern "C"

{

int yyparse(void);

int yylex(void);

int yywrap(void);

void yyerror(const char *);

/*int yydebug;*/

}

/*====================================== =================================LEX=YAC C=SETTINGS=============*/

extern char yytext[];

#define YYDEBUG_LEXER_TEXT yytext

/*====================================== =================================PROGRAM =SETTINGS==============*/

#include <stdio.h>

#include <stdarg.h> /* For function with variable number of parameters */

#include <iostream>

#include <fstream>

#include <string.h>

char* uniteStrings (const int number_of_parameters, ...);

std::fstream file_output;

%}

%{

/*====================================== ======================================== ======================================== ======================================== ======================================== =*/

/*====================================== ======================================== ======================================== ======================================== ======================================== =*/

/*====================================== ======================================== ======================================== ======================================== ======================================== =*/

%}

%%

/*====================================== ======================================== ======================================== ===C=GRAMMAR===================*/

primary_expression

: IDENTIFIER

{ $$ = uniteStrings (1, $1); }

| constant

{ $$ = uniteStrings (1, $1); }

| string

{ $$ = uniteStrings (1, $1); }

| '(' expression ')'

{ $$ = uniteStrings (3, $1, $2, $3); }

| generic_selection

{ $$ = uniteStrings (1, $1); }

;

constant

: I_CONSTANT /* includes character_constant */

{ $$ = uniteStrings (1, $1); }

| F_CONSTANT

{ $$ = uniteStrings (1, $1); }

| ENUMERATION_CONSTANT /* after it has been defined as such */

{ $$ = uniteStrings (1, $1); }

;

input

int main ()

{

printf ("Hello, World!!!");

if (0 && x)

{

printf ("Hi!!");

}

return 0;

}

output

int main ( )

{

printf ( "Hello, World!!!" ) ;

if ( 0 && x )

{

printf ( "Hi!!" ) ;

}

return 0 ;

}

C_grammar_lex

%e 1019

%p 2807

%n 371

%k 284

%a 1213

%o 1117

%{

/*====================================== ======================================== ==========================SETS========== =========================*/

%}

O [0-7]

D [0-9]

NZ [1-9]

L [a-zA-Z_]

A [a-zA-Z_0-9]

H [a-fA-F0-9]

HP (0[xX])

E ([Ee][+-]?{D}+)

P ([Pp][+-]?{D}+)

FS (f|F|l|L)

IS (((u|U)(l|L|ll|LL)?)|((l|L|ll|LL)(u|U)?) )

CP (u|U|L)

SP (u8|u|U|L)

ES (\\(['"\?\\abfnrtv]|[0-7]{1,3}|x[a-fA-F0 -9]+))

WS [ \t\v\n\f]

%{

/*====================================== ======================================== ==========================C=DECLARATIONS =========================*/

%}

%{

/*====================================== =================================SYSTEM= SETTINGS===============*/

/*#include "y.tab.h"*/ /* For compilation using C */

#include "C_grammar_yacc.h" /* For compilation using C++ */

extern YYSTYPE yylval;

extern void yyerror(const char *); /* prints grammar violation message */

extern int sym_type(const char *); /* returns type from symbol table */

#define sym_type(identifier) IDENTIFIER /* with no symbol table, fake it */

static void comment(void);

static int check_type(void);

#define YYSTYPE char*

/*====================================== =================================PROGRAM =SETINGS===============*/

#include <stdio.h>

%}

%%

%{

/*====================================== ======================================== ==========================COMMENTS====== =========================*/

%}

"/*" { comment(); }

"//".* { /* consume //-comment */ }

%{

/*====================================== ======================================== ==========================KEY=WORDS===== =========================*/

%}

"auto" {

printf ("%s", yytext);

return(AUTO);

}

"break" {

printf ("%s", yytext);

return(BREAK);

}

"case" {

printf ("%s", yytext);

return(CASE);

}

"char" {

printf ("%s", yytext);

return(CHAR);

}

"const" {

printf ("%s", yytext);

return(CONST);

}

"continue" {

printf ("%s", yytext);

return(CONTINUE);

}

"default" {

printf ("%s", yytext);

return(DEFAULT);

}

"do" {

printf ("%s", yytext);

return(DO);

}

"double" {

printf ("%s", yytext);

return(DOUBLE);

}

"else" {

printf ("%s", yytext);

return(ELSE);

}

"enum" {

printf ("%s", yytext);

return(ENUM);

}

"extern" {

printf ("%s", yytext);

return(EXTERN);

}

"float" {

printf ("%s", yytext);

return(FLOAT);

}

"for" {

printf ("%s", yytext);

return(FOR);

}

"goto" {

printf ("%s", yytext);

return(GOTO);

}

"if" {

printf ("%s", yytext);

return(IF);

}

"inline" {

printf ("%s", yytext);

return(INLINE);

}

"int" {

printf ("%s", yytext);

return(INT);

}

"long" {

printf ("%s", yytext);

return(LONG);

}

"register" {

printf ("%s", yytext);

return(REGISTER);

}

"restrict" {

printf ("%s", yytext);

return(RESTRICT);

}

"return" {

printf ("%s", yytext);

return(RETURN);

}

"short" {

printf ("%s", yytext);

return(SHORT);

}

"signed" {

printf ("%s", yytext);

return(SIGNED);

}

"sizeof" {

printf ("%s", yytext);

return(SIZEOF);

}

C_grammar_yacc

%token IDENTIFIER I_CONSTANT F_CONSTANT STRING_LITERAL FUNC_NAME SIZEOF

%token PTR_OP INC_OP DEC_OP LEFT_OP RIGHT_OP LE_OP GE_OP EQ_OP NE_OP

%token AND_OP OR_OP MUL_ASSIGN DIV_ASSIGN MOD_ASSIGN ADD_ASSIGN

%token SUB_ASSIGN LEFT_ASSIGN RIGHT_ASSIGN AND_ASSIGN

%token XOR_ASSIGN OR_ASSIGN

%token TYPEDEF_NAME ENUMERATION_CONSTANT

%token TYPEDEF EXTERN STATIC AUTO REGISTER INLINE

%token CONST RESTRICT VOLATILE

%token BOOL CHAR SHORT INT LONG SIGNED UNSIGNED FLOAT DOUBLE VOID

%token COMPLEX IMAGINARY

%token STRUCT UNION ENUM ELLIPSIS

%token CASE DEFAULT IF ELSE SWITCH WHILE DO FOR GOTO CONTINUE BREAK RETURN

%token ALIGNAS ALIGNOF ATOMIC GENERIC NORETURN STATIC_ASSERT THREAD_LOCAL

%start translation_unit

%{

/*====================================== =================================SYSTEM= SETTINGS===============*/

/* For compilation using C++ */

extern "C"

{

int yyparse(void);

int yylex(void);

int yywrap(void);

void yyerror(const char *);

/*int yydebug;*/

}

extern char yytext[];

#define YYDEBUG_LEXER_TEXT yytext

/*====================================== =================================PROGRAM =SETTINGS==============*/

#include <stdio.h>

%}

%%

/*====================================== ======================================== ======================================== ===C=GRAMMAR===================*/

primary_expression

: IDENTIFIER

| constant

| string

| '(' expression ')'

| generic_selection

;

constant

: I_CONSTANT /* includes character_constant */

| F_CONSTANT

| ENUMERATION_CONSTANT /* after it has been defined as such */

;

enumeration_constant /* before it has been defined as such */

: IDENTIFIER

;

string

: STRING_LITERAL

| FUNC_NAME

;

generic_selection

: GENERIC '(' assignment_expression ',' generic_assoc_list ')'

;

generic_assoc_list

: generic_association

| generic_assoc_list ',' generic_association

;

generic_association

: type_name ':' assignment_expression

| DEFAULT ':' assignment_expression

;

postfix_expression

: primary_expression

| postfix_expression '[' expression ']'

| postfix_expression '(' ')'

| postfix_expression '(' argument_expression_list ')'

| postfix_expression '.' IDENTIFIER

| postfix_expression PTR_OP IDENTIFIER

| postfix_expression INC_OP

| postfix_expression DEC_OP

| '(' type_name ')' '{' initializer_list '}'

| '(' type_name ')' '{' initializer_list ',' '}'

;

argument_expression_list

: assignment_expression

| argument_expression_list ',' assignment_expression

;

unary_expression

: postfix_expression

| INC_OP unary_expression

| DEC_OP unary_expression

| unary_operator cast_expression

| SIZEOF unary_expression

| SIZEOF '(' type_name ')'

| ALIGNOF '(' type_name ')'

;

unary_operator

: '&'

| '*'

| '+'

| '-'

| '~'

| '!'

;

cast_expression

: unary_expression

| '(' type_name ')' cast_expression

;

multiplicative_expression

: cast_expression

| multiplicative_expression '*' cast_expression

| multiplicative_expression '/' cast_expression

| multiplicative_expression '%' cast_expression

;

additive_expression

: multiplicative_expression

| additive_expression '+' multiplicative_expression

| additive_expression '-' multiplicative_expression

;

shift_expression

: additive_expression

| shift_expression LEFT_OP additive_expression

| shift_expression RIGHT_OP additive_expression

;

relational_expression

: shift_expression

| relational_expression '<' shift_expression

| relational_expression '>' shift_expression

| relational_expression LE_OP shift_expression

| relational_expression GE_OP shift_expression

;

equality_expression

: relational_expression

| equality_expression EQ_OP relational_expression

| equality_expression NE_OP relational_expression

;

and_expression

: equality_expression

| and_expression '&' equality_expression

;

exclusive_or_expression

: and_expression

| exclusive_or_expression '^' and_expression

;

inclusive_or_expression

: exclusive_or_expression

| inclusive_or_expression '|' exclusive_or_expression

;

logical_and_expression

: inclusive_or_expression

| logical_and_expression AND_OP inclusive_or_expression

;

logical_or_expression

: logical_and_expression

| logical_or_expression OR_OP logical_and_expression

;

conditional_expression

: logical_or_expression

| logical_or_expression '?' expression ':' conditional_expression

;

assignment_expression

: conditional_expression

| unary_expression assignment_operator assignment_expression

;

assignment_operator

: '='

| MUL_ASSIGN

| DIV_ASSIGN

| MOD_ASSIGN

| ADD_ASSIGN

| SUB_ASSIGN

| LEFT_ASSIGN

| RIGHT_ASSIGN

| AND_ASSIGN

| XOR_ASSIGN

| OR_ASSIGN

;

expression

: assignment_expression

| expression ',' assignment_expression

;

constant_expression

: conditional_expression /* with constraints */

;

declaration

: declaration_specifiers ';'

| declaration_specifiers init_declarator_list ';'

| static_assert_declaration

;

declaration_specifiers

: storage_class_specifier declaration_specifiers

| storage_class_specifier

| type_specifier declaration_specifiers

| type_specifier

| type_qualifier declaration_specifiers

| type_qualifier

| function_specifier declaration_specifiers

| function_specifier

| alignment_specifier declaration_specifiers

| alignment_specifier

;

init_declarator_list

: init_declarator

| init_declarator_list ',' init_declarator

;

init_declarator

: declarator '=' initializer

| declarator

;

storage_class_specifier

: TYPEDEF /* identifiers must be flagged as TYPEDEF_NAME */

| EXTERN

| STATIC

Прочти меня!!!

Файл скачан с сайта StudIzba.com

При копировании или цитировании материалов на других сайтах обязательно используйте ссылку на источник

Картинка-подпись
Хочешь зарабатывать на СтудИзбе больше 10к рублей в месяц? Научу бесплатно!
Начать зарабатывать

Комментарии

Поделитесь ссылкой:
Бесплатно
Рейтинг-
0
0
0
0
0
Поделитесь ссылкой:
Сопутствующие материалы
Свежие статьи
Популярно сейчас
Зачем заказывать выполнение своего задания, если оно уже было выполнено много много раз? Его можно просто купить или даже скачать бесплатно на СтудИзбе. Найдите нужный учебный материал у нас!
Ответы на популярные вопросы
Да! Наши авторы собирают и выкладывают те работы, которые сдаются в Вашем учебном заведении ежегодно и уже проверены преподавателями.
Да! У нас любой человек может выложить любую учебную работу и зарабатывать на её продажах! Но каждый учебный материал публикуется только после тщательной проверки администрацией.
Вернём деньги! А если быть более точными, то автору даётся немного времени на исправление, а если не исправит или выйдет время, то вернём деньги в полном объёме!
Да! На равне с готовыми студенческими работами у нас продаются услуги. Цены на услуги видны сразу, то есть Вам нужно только указать параметры и сразу можно оплачивать.
Отзывы студентов
Ставлю 10/10
Все нравится, очень удобный сайт, помогает в учебе. Кроме этого, можно заработать самому, выставляя готовые учебные материалы на продажу здесь. Рейтинги и отзывы на преподавателей очень помогают сориентироваться в начале нового семестра. Спасибо за такую функцию. Ставлю максимальную оценку.
Лучшая платформа для успешной сдачи сессии
Познакомился со СтудИзбой благодаря своему другу, очень нравится интерфейс, количество доступных файлов, цена, в общем, все прекрасно. Даже сам продаю какие-то свои работы.
Студизба ван лав ❤
Очень офигенный сайт для студентов. Много полезных учебных материалов. Пользуюсь студизбой с октября 2021 года. Серьёзных нареканий нет. Хотелось бы, что бы ввели подписочную модель и сделали материалы дешевле 300 рублей в рамках подписки бесплатными.
Отличный сайт
Лично меня всё устраивает - и покупка, и продажа; и цены, и возможность предпросмотра куска файла, и обилие бесплатных файлов (в подборках по авторам, читай, ВУЗам и факультетам). Есть определённые баги, но всё решаемо, да и администраторы реагируют в течение суток.
Маленький отзыв о большом помощнике!
Студизба спасает в те моменты, когда сроки горят, а работ накопилось достаточно. Довольно удобный сайт с простой навигацией и огромным количеством материалов.
Студ. Изба как крупнейший сборник работ для студентов
Тут дофига бывает всего полезного. Печально, что бывают предметы по которым даже одного бесплатного решения нет, но это скорее вопрос к студентам. В остальном всё здорово.
Спасательный островок
Если уже не успеваешь разобраться или застрял на каком-то задание поможет тебе быстро и недорого решить твою проблему.
Всё и так отлично
Всё очень удобно. Особенно круто, что есть система бонусов и можно выводить остатки денег. Очень много качественных бесплатных файлов.
Отзыв о системе "Студизба"
Отличная платформа для распространения работ, востребованных студентами. Хорошо налаженная и качественная работа сайта, огромная база заданий и аудитория.
Отличный помощник
Отличный сайт с кучей полезных файлов, позволяющий найти много методичек / учебников / отзывов о вузах и преподователях.
Отлично помогает студентам в любой момент для решения трудных и незамедлительных задач
Хотелось бы больше конкретной информации о преподавателях. А так в принципе хороший сайт, всегда им пользуюсь и ни разу не было желания прекратить. Хороший сайт для помощи студентам, удобный и приятный интерфейс. Из недостатков можно выделить только отсутствия небольшого количества файлов.
Спасибо за шикарный сайт
Великолепный сайт на котором студент за не большие деньги может найти помощь с дз, проектами курсовыми, лабораторными, а также узнать отзывы на преподавателей и бесплатно скачать пособия.
Популярные преподаватели
Добавляйте материалы
и зарабатывайте!
Продажи идут автоматически
5247
Авторов
на СтудИзбе
422
Средний доход
с одного платного файла
Обучение Подробнее