implemented part of parser

This commit is contained in:
Aaro Koivukangas
2024-01-30 20:34:58 +02:00
parent 0e09d2dffb
commit 95230ae112
5 changed files with 85 additions and 5 deletions
+3
View File
@@ -0,0 +1,3 @@
*.hi
*.o
Main
View File
+10 -2
View File
@@ -1,6 +1,14 @@
module Main (main) where module Main (main) where
import Lib import System.Environment
import Parser
main :: IO () main :: IO ()
main = someFunc main = do args <- getArgs
putStrLn . readExpr $ args !! 0
readExpr :: String -> String
readExpr str =
case parseToken str of
Left err -> "No match: " ++ show err
Right val -> show val
+72
View File
@@ -0,0 +1,72 @@
module Parser (
parseToken,
parseRegister,
parseInstruction,
parseOperand,
Token ) where
import Data.Char
import Data.List.Split
parseToken :: String -> Either String Token
parseToken str = case parseOperand str of
Just token -> Right token
Nothing -> Left "No token found"
parseRegister :: String -> Maybe Token
parseRegister (x:xs)
| x == 'R' && not (null xs) && all isDigit xs = Just $ Register (read xs)
| otherwise = Nothing
dataInsructions = ["LOAD", "STORE", "IN", "OUT"]
arithmeticInstructions = ["ADD", "SUB", "MUL", "DIV", "MOD"]
logicInstructions = ["AND", "OR", "XOR", "NOT", "SHL", "SHR", "SHRA", "COMP"]
branchingInstructions = ["JUMP", "JNEG", "JZER", "JPOS", "JNNEG", "JNZER", "JNPOS", "JLES", "JEQU", "JGRE", "JNLES", "JNEQU", "JNGRE"]
stackInstructions = ["PUSH", "POP", "PUSHR", "POPR"]
subroutineInstructions = ["CALL", "EXIT"]
systemcallInsructions = ["SVC"]
compilerInsructions = ["EQU", "DC", "DS", "DEF"]
otherInstructions = ["NOP"]
allInsructions = dataInsructions ++ arithmeticInstructions ++ logicInstructions ++ branchingInstructions ++ stackInstructions ++ subroutineInstructions ++ systemcallInsructions ++ compilerInsructions ++ otherInstructions
parseInstruction :: String -> Maybe Token
parseInstruction str =
case str `elem` allInsructions of
True -> Just $ Instruction str
False -> Nothing
variables = [Variable "X", Variable "Y"]
parseOperand :: String -> Maybe Token
parseOperand str = Just $ Operand str immediateOperand indirectOperand indexed
where
immediateOperand = '=' `elem` str
indirectOperand = '@' `elem` str
value = if immediateOperand || indirectOperand
then tail str
else str
indexed = '(' `elem` value && ')' `elem` value
registers = if indexed
then endBy "(" $ init value
else [str]
data Token = Register Int
| Instruction String
| Comment String
| Operand String Bool Bool Bool
| MemoryAddress String
| Value Integer
| Variable String
| Error String
deriving (Show, Eq)
-3
View File
@@ -1,3 +0,0 @@
module Register
where