Code archives/Miscellaneous/Simple Math Compiler
This code has been declared by its author to be Public Domain code.
Download source code
| |||||
Digit = "0" | "1" | "2" | ... | "9"; Number = Digit {Digit}; Factor = Number | "(" Expression ")"; Term = Factor {("*" | "/") Factor}; Expression = Term {("+" | "-") Factor}; Don't use white spaces! It's only a little example to show, how easy it is to do this. Based on http://www.informatik.uni-bonn.de/III/lehre/vorlesungen/Informatik_I/WS05/Folien/VLWS0506-10.pdf Example: "6*7+2*4" will output push 6 push 7 pop ebx pop eax mul eax, ebx push eax push 2 push 4 pop ebx pop eax mul eax, ebx push eax pop ebx pop eax add eax, ebx push eax pop eax ; Result: 50 cu olli | |||||
Global In$ Global Position% Global Token% In$ = Input(">")+Chr(13) Position% = 1 Parse() WaitKey() End Function Parse() GetToken() Command() End Function Function Error() Print "Parse error" WaitKey() End End Function Function GetToken() If Position% > Len(In$) Then Error() Token% = Asc(Mid(In$, Position%, 1)) Position% = Position% + 1 End Function Function Match(Char%) If Token% = Char% Then GetToken() Else Error() EndIf End Function Function Command() Local Result% Result% = Expression() If Token% = 13 Then Print "pop eax" Print "; Result: "+Result% Print "" Else Error() EndIf End Function Function Expression%() Local Result% Result = Term() While Token% = Asc("+") Or Token% = Asc("-") If Token% = Asc("+") GetToken() Result% = Result% + Term() Print "pop ebx" Print "pop eax" Print "add eax, ebx" Print "push eax" Else GetToken() Result% = Result% - Term() Print "pop ebx" Print "pop eax" Print "sub eax, ebx" Print "push eax" EndIf Wend Return Result% End Function Function Term%() Local Result% Result = Factor() While Token% = Asc("*") Or Token% = Asc("/") If Token% = Asc("*") Then GetToken() Result% = Result% * Factor() Print "pop ebx" Print "pop eax" Print "mul eax, ebx" Print "push eax" Else GetToken() Result = Result% / Factor() Print "pop ebx" Print "pop eax" Print "div eax, ebx" Print "push eax" EndIf Wend Return Result% End Function Function Factor%() Local Result% If Token% = Asc("(") Then Match(Asc("(")) Result% = Expression() Match(Asc(")")) Else Result% = Number() EndIf Return Result% End Function Function Number%() Local Result% While Token% => Asc("0") And Token% <= Asc("9") Result% = Result%*10 + Digit() Wend Print "push "+Result% Return Result% End Function Function Digit%() Local Result% If Token% => Asc("0") And Token% <= Asc("9") Then Result% = Token% - Asc("0") Match(Token%) Else Error() EndIf Return Result% End Function |
Comments
| ||
Interesting |
Code Archives Forum