理解syntactical sugar

  • Overview

    If a language provides convenient, compact shortcuts, then those shortcuts may be described as syntactical sugar, a term coined in 1964.

    The built-in dictionary data structure in Python is syntactic sugar for an associative matrix/list.

  • Syntactic sugar

    Syntactic sugar is syntax within a programming language that is designed to make things easier to read or to express.

    It makes the language “sweeter” for human use: things can be expressed more clearly, more concisely, or in an alternative style that some may prefer.

    The term syntactic sugar was coined by Peter J. Landin in 1964.

  • References

  1. Stueben, M. Good Habits for Great Coding. (Apress, 2018). doi:10.1007/978-1-4842-3459-4.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,你的问题是如何用flex和bison实现C--语法分析器,并在检测到语法错误时输出错误信息吗? 首先,你需要编写一个flex文件,用于将C--源代码转换为一系列标记,比如关键字、标识符、操作符等。然后,你需要编写一个bison文件,用于定义C--语法规则,并生成语法分析器。 以下是一个简单的flex文件示例,用于将C--源代码分解为标记: ```flex %{ #include "y.tab.h" %} %% "if" { return IF; } "else" { return ELSE; } "while" { return WHILE; } "int" { return INT; } "float" { return FLOAT; } "+" { return ADDOP; } "-" { return SUBOP; } "*" { return MULOP; } "/" { return DIVOP; } "(" { return LPAREN; } ")" { return RPAREN; } ";" { return SEMICOLON; } [0-9]+ { yylval.num = atoi(yytext); return NUMBER; } [a-zA-Z][a-zA-Z0-9]*{ yylval.str = strdup(yytext); return IDENTIFIER; } [ \t\n] ; /* skip whitespace */ . ; /* skip unknown characters */ %% int yywrap() { return 1; } ``` 上面的代码定义了一些基本的标记,比如关键字、操作符、括号等。它还定义了识别数字和标识符的正则表达式,并将它们存储在yylval结构体中,以便bison可以访问它们。 接下来是一个简单的bison文件示例,用于定义C--语法规则: ```bison %{ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "lex.yy.h" %} %token IF ELSE WHILE INT FLOAT ADDOP SUBOP MULOP DIVOP LPAREN RPAREN SEMICOLON NUMBER IDENTIFIER %% program: stmt_list { printf("Syntactical Correct.\n"); } ; stmt_list: stmt SEMICOLON stmt_list | stmt SEMICOLON ; stmt: expr | IF LPAREN expr RPAREN stmt | IF LPAREN expr RPAREN stmt ELSE stmt | WHILE LPAREN expr RPAREN stmt ; expr: term ADDOP term | term SUBOP term ; term: factor MULOP factor | factor DIVOP factor ; factor: LPAREN expr RPAREN | NUMBER | IDENTIFIER ; %% int main(int argc, char *argv[]) { yyparse(); return 0; } void yyerror(char *msg) { printf("Error type (Syntactical) at line %d: %s\n", yylineno, msg); } ``` 上面的代码定义了C--语法规则,并在检测到语法错误时输出错误信息。它还包括一个yyerror函数,用于输出错误信息。 最后,你需要将这两个文件编译成可执行文件,然后运行它来分析C--源代码。 希望这个例子对你有所帮助!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值