Compare commits

..

No commits in common. "d83106358fbf7293a112d6f3c75f6113e546aa09" and "f27939ee67e9962c0cea0060b56cc9f63edcf457" have entirely different histories.

12 changed files with 64 additions and 294 deletions

View File

@ -1,15 +1,10 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Library</OutputType>
<TargetFramework>netstandard2.0</TargetFramework>
<LangVersion>latest</LangVersion>
<ImplicitUsings>disable</ImplicitUsings>
<Nullable>disable</Nullable>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<RollForward>LatestMajor</RollForward>
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
</PropertyGroup>
<ItemGroup>
<Compile Remove="out\MainClass.cs" />
</ItemGroup>
</Project>

View File

@ -1,12 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<AssemblyName>FusionCalculator</AssemblyName>
<TargetFramework>net8.0</TargetFramework>
<LangVersion>latest</LangVersion>
<ImplicitUsings>disable</ImplicitUsings>
<Nullable>disable</Nullable>
</PropertyGroup>
</Project>

View File

@ -1,44 +0,0 @@
# FusionCalculator
The calculator written in [Fusion language](https://github.com/fusionlanguage/fut). Can be translated to C and C#. Can be compiled as executable or library.
### Building
Requirements: fut, bash, dotnet8 (for c#), gcc (for C)
Just generate C# source files:
```shell
./build_cs.sh --translate-only
```
Build C# executable:
```shell
./build_cs.sh
```
Build C executable:
```shell
./build_c.sh
```
Build C executable with debug symbols:
```shell
./build_c.sh --debug
```
## Executable usage
Just call exe file in bin/ with math expression arguments:
```shell
bin/FusionCalculator.exe 1+2
3
bin/FusionCalculator.exe '11/(99-88)'
1
bin/FusionCalculator.exe '-1+6*(-2)'
-13
```
## Library usage
The public interface is very simple:
```cs
namespace FusionCalculator {
public static class Calculator {
public static double Calculate(string);
}
}
```
Just call Calculate and get the result!

24
build_c.sh Executable file → Normal file
View File

@ -6,30 +6,12 @@ BIN_FILE="bin/FusionCalculator.exe"
SRC_FILES="$(find src/ -name '*.fu')"
WARNINGS="-Wall -Wno-unused-value -Wno-unused-function -Wno-unused-variable -Wno-discarded-qualifiers"
INCLUDES="$(pkg-config --cflags glib-2.0)"
if [[ $1 == '--debug' ]]; then
COMPILER_ARGS="-O0 -g"
else
COMPILER_ARGS="-O2"
fi
COMPILER_ARGS="-O0 -g"
LINKER_ARGS="$(pkg-config --libs glib-2.0) -lm"
rm -rf out bin
mkdir out bin
echo "------------[fut]------------"
fut -l c -D C -o "$OUT_FILE" $SRC_FILES
args="-l c -D C -o "$OUT_FILE" $SRC_FILES"
if [[ $1 == '--implement-math-functions' || $2 == '--implement-math-functions' ]]; then
args="$args -D IMPLEMENT_MATH_FUNCTIONS"
fi
echo fut $args
fut $args
if [[ $1 != '--translate-only' && $2 != '--translate-only' ]]; then
echo "------------[gcc]------------"
args="$WARNINGS $COMPILER_ARGS "$OUT_FILE" -o "$BIN_FILE" $INCLUDES $LINKER_ARGS"
echo gcc $args
gcc $args
fi
gcc $WARNINGS $COMPILER_ARGS "$OUT_FILE" -o "$BIN_FILE" $INCLUDES $LINKER_ARGS

15
build_cs.sh Executable file → Normal file
View File

@ -12,19 +12,10 @@ done
for src_file in $SRC_FILES; do
echo "---------[$src_file]---------"
out_file="out/$(basename $src_file .fu).cs"
args="-l cs -D CS -n FusionCalculator $INCLUDES -o $out_file $src_file"
if [[ $1 == '--implement-math-functions' || $2 == '--implement-math-functions' ]]; then
args="$args -D IMPLEMENT_MATH_FUNCTIONS"
fi
echo fut $args
echo "fu $args"
fut $args
done
if [[ $1 != '--translate-only' && $2 != '--translate-only' ]]; then
echo "---------[FusionCalculator.csproj]---------"
args="build -c Release FusionCalculator.exe.csproj -o bin"
echo dotnet $args
dotnet $args
fi
echo "---------[FusionCalculator.csproj]---------"
dotnet build FusionCalculator.csproj -o bin

View File

@ -11,43 +11,13 @@ abstract class FunctionCallExpression : IExpression {
}
class FunctionCallExpressionSin : FunctionCallExpression {
internal override double FunctionImplementation(double x) {
#if IMPLEMENT_MATH_FUNCTIONS
return MyMath.Sin(x);
#else
return Math.Sin(x);
#endif
}
internal override double FunctionImplementation(double x) => Math.Sin(x);
}
class FunctionCallExpressionCos : FunctionCallExpression {
internal override double FunctionImplementation(double x) {
#if IMPLEMENT_MATH_FUNCTIONS
return MyMath.Cos(x);
#else
return Math.Cos(x);
#endif
}
internal override double FunctionImplementation(double x) => Math.Cos(x);
}
class FunctionCallExpressionTg : FunctionCallExpression {
internal override double FunctionImplementation(double x){
#if IMPLEMENT_MATH_FUNCTIONS
return MyMath.Tg(x);
#else
return Math.Tan(x);
#endif
}
}
class FunctionCallExpressionCtg : FunctionCallExpression {
internal override double FunctionImplementation(double x) {
#if IMPLEMENT_MATH_FUNCTIONS
return MyMath.Ctg(x);
#else
return 1 / Math.Tan(x);
#endif
}
class FunctionCallExpressionTan : FunctionCallExpression {
internal override double FunctionImplementation(double x) => Math.Tan(x);
}
class FunctionCallExpressionAsin : FunctionCallExpression {
@ -56,13 +26,10 @@ class FunctionCallExpressionAsin : FunctionCallExpression {
class FunctionCallExpressionAcos : FunctionCallExpression {
internal override double FunctionImplementation(double x) => Math.Acos(x);
}
class FunctionCallExpressionAtg : FunctionCallExpression {
class FunctionCallExpressionAtan : FunctionCallExpression {
internal override double FunctionImplementation(double x) => Math.Atan(x);
}
class FunctionCallExpressionActg : FunctionCallExpression {
internal override double FunctionImplementation(double x) => Math.Atan(1 / x);
}
class FunctionCallExpressionLn : FunctionCallExpression{
class FunctionCallExpressionLog : FunctionCallExpression{
internal override double FunctionImplementation(double x) => Math.Log(x);
}

View File

@ -1,50 +0,0 @@
//
// My implementation of math functions using Taylor (Maclaurin) series
// https://en.wikipedia.org/wiki/Taylor_series#List_of_Maclaurin_series_of_some_common_functions
//
public class MyMath {
/// TODO: fix fail on tg(pi/2), tg(pi*), ctg(pi*2)
static double ClampRadians(double x){
int quotient = 0;
double pi2 = 2*Math.PI;
native {
quotient = (int)(x / pi2);
}
x -= pi2 * quotient;
return x;
}
public static double Sin(double x){
x = ClampRadians(x);
int iters = 16;
double pow = x;
double fact = 1;
double result = x;
for(int i = 3; i <= (2*iters+1); i+=2){
pow *= x*x; // x power +2
fact *= i * (i-1); // making i! from (i-2)!
fact *= -1; // change sign every iteration
result += pow/fact;
}
return result;
}
public static double Cos(double x){
x = ClampRadians(x);
int iters = 16;
double pow = 1;
double fact = 1;
double result = 1;
for(int i = 2; i <= (2*iters); i+=2){
pow *= x*x; // x power +2
fact *= i * (i-1); // making i! from (i-2)!
fact *= -1; // change sign every iteration
result += pow/fact;
}
return result;
}
public static double Tg(double x) => Sin(x)/Cos(x);
public static double Ctg(double x) => Cos(x)/Sin(x);
}

View File

@ -29,26 +29,17 @@ class OperatorExpressionDiv : OperatorExpression {
}
class OperatorExpressionMod : OperatorExpression {
// returns if b>0 then returns a%b else returns a
internal override double OperatorImplementation(double a, double b) {
if(a == 0)
return b;
if(b == 0)
if(b <= 0)
return a;
if(a > 0){
if(b > 0)
while(a-b >= 0)
while(a >= b)
a -= b;
else
while(a+b >= 0)
a += b;
}
else {
if(b > 0)
while(a+b <= 0)
while(a <= b)
a += b;
else
while(a-b <= 0)
a -= b;
}
return a;
}

View File

@ -37,7 +37,7 @@ class Lexer {
internal List<Token()> Lex!(string exprStr){
ExprStr = exprStr;
for(i=0; i < ExprStr.Length; i++) {
while (i < ExprStr.Length) {
switch (ExprStr[i]) {
// end token, add new predifined token and move next
case '(': AddStaticToken(TokBracketOpen); break;
@ -47,33 +47,21 @@ class Lexer {
case '%': AddStaticToken(TokMod); break;
case '/': AddStaticToken(TokDiv); break;
case '+': AddStaticToken(TokAdd); break;
case '-':
// if '-' is not the first char and previous char isn't '(' or 'e' or 'E'
if(i != 0 && ExprStr[i-1] != '('
&& ExprStr[i-1] != 'e' && ExprStr[i-1] != 'E')
AddStaticToken(TokSub);
// else '-' is a part of numeric expression
break;
case 'e':
case 'E':
// if token starts with 'E' it is a literal
if(i == tokBegin)
tokType = Token.Type_Literal;
// else 'E' is a part of literal or number (sientific notation)
break;
case '-': AddStaticToken(TokSub); break;
// try end token and skip current char
case ' ': case '\t': case '\n': case '\r':
TryEndToken();
tokBegin++;
i++;
break;
// move next
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
case '.':
i++;
break;
// set type from Numeric to Literal
default:
tokType = Token.Type_Literal;
i++;
break;
}
}
@ -98,6 +86,6 @@ class Lexer {
TokenStorage.Add();
TokenStorage[TokenStorage.Count-1] = tok;
tokType = Token.Type_Number;
tokBegin = i+1;
tokBegin = ++i;
}
}

View File

@ -2,15 +2,14 @@ public static class MainClass {
public static void Main(string[] args){
#if CS
native {
System.Globalization.CultureInfo.DefaultThreadCurrentCulture =
System.Globalization.CultureInfo.InvariantCulture;
System.Globalization.CultureInfo.DefaultThreadCurrentCulture = System.Globalization.CultureInfo.InvariantCulture;
}
#endif
string() joined = "";
foreach(string arg in args){
joined += arg + " ";
joined += arg;
}
double result = Calculator.Calculate(joined);
Console.WriteLine(result);
double rezult = Calculator.Calculate(joined);
Console.WriteLine(rezult);
}
}

View File

@ -2,9 +2,11 @@ class Parser {
List<Token()> TokenStorage;
IExpression# RootExpression;
TokenLinkedList() TokensInRPN;
Token() TokZero;
internal Parser(){
RootExpression = new NumericExpression(); // NaN
TokZero = Token.Create("0", 0, 1, Token.Type_Number);
}
internal IExpression# Parse!(List<Token()> tokens){
@ -24,6 +26,8 @@ class Parser {
// Implementation of https://en.wikipedia.org/wiki/Shunting_yard_algorithm
void SortTokensInRPN!(){
Stack<Token>() RPNStack;
// is needed for negative numbers recognition
int prevTokType = Token.Type_BracketOpen;
for(int i = 0; i < TokenStorage.Count; i++){
Token tok = TokenStorage[i];
@ -39,7 +43,8 @@ class Parser {
case Token.Type_OperatorMod:
case Token.Type_OperatorAdd:
case Token.Type_OperatorSub:
case Token.Type_Literal:
if(type == Token.Type_OperatorSub && prevTokType == Token.Type_BracketOpen)
TokensInRPN.AddToEnd(TokZero);
while(RPNStack.Count != 0 && RPNStack.Peek().GetTokType() >= type){
Token op2 = RPNStack.Pop();
TokensInRPN.AddToEnd(op2);
@ -57,10 +62,15 @@ class Parser {
TokensInRPN.AddToEnd(op2);
}
break;
case Token.Type_Literal:
ThrowError($"token '{tok.GetStr()}' isn't implemented");
break;
default:
ThrowError($"unexpected token type '{type}'");
break;
}
prevTokType = type;
}
// add remaining operators
@ -78,31 +88,30 @@ class Parser {
while(tokenNode != null){
Token tok = tokenNode.GetValue();
int type = tok.GetTokType();
string() str = tok.GetStr();
switch(type){
case Token.Type_Number:
NumericExpression# num = new NumericExpression();
num.Init(StringToDouble(str));
num.Init(StringToDouble(tok.GetStr()));
expressionStack.Push(num);
break;
case Token.Type_OperatorPow:
PushOperatorExpression(expressionStack, str, new OperatorExpressionPow());
PushOperatorExpression(expressionStack, tok, new OperatorExpressionPow());
break;
case Token.Type_OperatorMul:
PushOperatorExpression(expressionStack, str, new OperatorExpressionMul());
PushOperatorExpression(expressionStack, tok, new OperatorExpressionMul());
break;
case Token.Type_OperatorDiv:
PushOperatorExpression(expressionStack, str, new OperatorExpressionDiv());
PushOperatorExpression(expressionStack, tok, new OperatorExpressionDiv());
break;
case Token.Type_OperatorMod:
PushOperatorExpression(expressionStack, str, new OperatorExpressionMod());
PushOperatorExpression(expressionStack, tok, new OperatorExpressionMod());
break;
case Token.Type_OperatorAdd:
PushOperatorExpression(expressionStack, str, new OperatorExpressionAdd());
PushOperatorExpression(expressionStack, tok, new OperatorExpressionAdd());
break;
case Token.Type_OperatorSub:
PushOperatorExpression(expressionStack, str, new OperatorExpressionSub());
PushOperatorExpression(expressionStack, tok, new OperatorExpressionSub());
break;
case Token.Type_BracketClose:
ThrowError("unexpected '('");
@ -111,56 +120,19 @@ class Parser {
ThrowError("unexpected ')'");
break;
case Token.Type_Literal:
switch(str){
case "sin":
PushFunctionExpression(expressionStack, str, new FunctionCallExpressionSin());
ThrowError($"token '{tok.GetStr()}' isn't implemented");
break;
case "cos":
PushFunctionExpression(expressionStack, str, new FunctionCallExpressionCos());
break;
case "tan":
case "tg":
PushFunctionExpression(expressionStack, str, new FunctionCallExpressionTg());
break;
case "ctg":
PushFunctionExpression(expressionStack, str, new FunctionCallExpressionCtg());
break;
case "asin":
PushFunctionExpression(expressionStack, str, new FunctionCallExpressionAsin());
break;
case "acos":
PushFunctionExpression(expressionStack, str, new FunctionCallExpressionAcos());
break;
case "atan":
case "atg":
case "arctg":
PushFunctionExpression(expressionStack, str, new FunctionCallExpressionAtg());
break;
case "actg":
case "arcctg":
PushFunctionExpression(expressionStack, str, new FunctionCallExpressionActg());
break;
case "ln":
PushFunctionExpression(expressionStack, str, new FunctionCallExpressionLn());
break;
default: {
ThrowError($"invalid literal '{str}'");
}
break;
}
break;
default: {
default:
ThrowError($"unexpected token type '{type}'");
}
break;
}
tokenNode = tokenNode.GetNext();
}
if(expressionStack.Count != 1)
ThrowError("");
if(expressionStack.Count == 1)
RootExpression = expressionStack.Pop();
else RootExpression = new NumericExpression(); // NaN
}
// returns the number or NaN
@ -182,9 +154,9 @@ class Parser {
return d;
}
void PushOperatorExpression(Stack<IExpression#>! expressionStack, string tokStr, OperatorExpression# opExpr) {
void PushOperatorExpression(Stack<IExpression#>! expressionStack, Token tok, OperatorExpression# opExpr) {
if(expressionStack.Count < 2){
ThrowError($"unexpected operator '{tokStr}'");
ThrowError($"unexpected operator '{tok.GetStr()}'");
return;
}
IExpression b = expressionStack.Pop();
@ -192,15 +164,6 @@ class Parser {
opExpr.Init(a, b);
expressionStack.Push(opExpr);
}
void PushFunctionExpression(Stack<IExpression#>! expressionStack, string tokStr, FunctionCallExpression# fExpr) {
if(expressionStack.Count < 1){
ThrowError($"unexpected function call '{tokStr}'");
return;
}
IExpression x = expressionStack.Pop();
fExpr.Init(x);
expressionStack.Push(fExpr);
}
static void ThrowError(string errmsg){
#if C

View File

@ -6,16 +6,16 @@ class Token {
// The Type is also the priority of the token in calculation (see Parser).
int Type;
public const int Type_Literal=11;
public const int Type_OperatorPow=10;
public const int Type_OperatorMul=9;
public const int Type_OperatorMod=8;
public const int Type_OperatorDiv=7;
public const int Type_OperatorAdd=6;
public const int Type_OperatorSub=5;
public const int Type_BracketOpen=3;
public const int Type_BracketClose=2;
public const int Type_Number=1;
public const int Type_BracketOpen=4;
public const int Type_BracketClose=3;
public const int Type_Number=2;
public const int Type_Literal=1;
internal static Token() Create(string str, int startIndex, int length, int type){
Token() tok = {