1 Star 0 Fork 0

jhkwei / Cal

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
CalLex.cpp 3.42 KB
一键复制 编辑 原始数据 按行查看 历史
jhkwei 提交于 2022-09-16 00:10 . cal
//CalLex.c
#include "CalLex.h"
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <ctype.h>
struct Lex *lex_init(char *data, int size)
{
if(size <= 0){
return NULL;
}
struct Lex *lex = (struct Lex *)calloc(1 ,sizeof(*lex));
assert(lex);
lex->data = (char *)calloc(1, size+1);
assert(lex->data);
memcpy(lex->data, data, size);
lex->size = size;
lex->p = lex->data;
return lex;
}
void lex_exit(struct Lex *lex)
{
if(lex == NULL){
return;
}
if(lex->data){
free(lex->data);
}
free(lex);
}
enum CalLexToken lex_readNumber(struct Lex *lex,struct Token *token, char c)
{
double ll = 0;
token->d = 0;
if(isdigit(c)){
ll = c - '0';
while(1){
c = lex_getNext(lex);
if(isdigit(c)){
ll = ll * 10 + (c - '0');
}else{
if(c != '.'){
lex_putBack(lex);
}
break;
}
}
}
double ls = 0;
int count = 10;
if(c == '.'){
c = lex_getNext(lex);
if(!isdigit(c)){
lex_putBack(lex);
}else{
ls = c - '0';
while(1){
c = lex_getNext(lex);
if(isdigit(c)){
ls = ls * 10 + (c - '0');
count *= 10;
}else{
lex_putBack(lex);
break;
}
}
}
}
token->d = ll + (ls*1.0000f/count);
return Lex_Number;
}
enum CalLexToken lex_readFun(struct Lex *lex, char c)
{
char name[4] = {0};
int count = 0;
name[count] = c;
count++;
while(count < 3){
char n = lex_getNext(lex);
if(n == '\0'){
printf("function name error\n");
return Lex_Nil;
}
if(isalpha(n)){
name[count] = n;
count++;
}else{
printf("function name error\n");
return Lex_Nil;
}
}
if(!strcmp(name,"cos")){
return Lex_Cos;
}
if(!strcmp(name,"sin")){
return Lex_Sin;
}
if(!strcmp(name,"tan")){
return Lex_Tan;
}
if(!strcmp(name,"cot")){
return Lex_Cot;
}
if(!strcmp(name,"log")){
return Lex_Log;
}
printf("unknown function name\n");
return Lex_Nil;
}
enum CalLexToken lex_item(struct Lex *lex,struct Token *token)
{
while(1){
char c = lex_getNext(lex);
switch (c) {
case '\0':return Lex_Eof;
case '(':return Lex_Begin;
case ')':return Lex_End;
case '+':return Lex_Plus;
case '-':return Lex_Minus;
case '*':return Lex_Mutil;
case '/':return Lex_Div;
case '^':return Lex_Pow;
default:
{
if(isspace(c)){
break;
}else if(isalpha(c)){
return lex_readFun(lex, c);
}else{
return lex_readNumber(lex, token, c);
}
}
}
}
return Lex_Nil;
}
char lex_getNext(struct Lex *lex)
{
return *lex->p++;
}
void lex_putBack(struct Lex *lex)
{
lex->p--;
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
C
1
https://gitee.com/jhkwei/cal.git
git@gitee.com:jhkwei/cal.git
jhkwei
cal
Cal
master

搜索帮助

344bd9b3 5694891 D2dac590 5694891