58e24788e24ddee28e000053.h 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. #pragma once
  2. #include <string>
  3. #include <vector>
  4. #include <unordered_map>
  5. std::vector<std::string_view> toArgs( const std::string_view line ) {
  6. std::vector<std::string_view> args;
  7. size_t pos = 0;
  8. for ( size_t i = 0; i < line.size(); ++i )
  9. {
  10. if ( line[i] == ' ' )
  11. {
  12. args.push_back( line.substr( pos, i - pos ) );
  13. pos = i + 1;
  14. }
  15. }
  16. args.push_back( line.substr( pos ) );
  17. return args;
  18. }
  19. bool isRegisterName( std::string_view line ) {
  20. return line.find_first_not_of( "abcdefghijklmnopqrstuvwxyz" ) == std::string_view::npos;
  21. }
  22. std::unordered_map<std::string, int> assembler( const std::vector<std::string> & program ) {
  23. std::unordered_map<std::string, int> regs;
  24. for ( int i = 0; i < static_cast<int>( program.size() ); ++i )
  25. {
  26. auto args = toArgs( program[static_cast<size_t>( i )] );
  27. if ( args[0] == "mov" )
  28. {
  29. regs[static_cast<std::string>( args[1] )]
  30. = isRegisterName( args[2] ) ? regs[static_cast<std::string>( args[2] )] : std::stoi( static_cast<std::string>( args[2] ) );
  31. } else if ( args[0] == "inc" )
  32. {
  33. regs[static_cast<std::string>( args[1] )] += 1;
  34. } else if ( args[0] == "dec" )
  35. {
  36. regs[static_cast<std::string>( args[1] )] -= 1;
  37. } else if ( args[0] == "jnz" )
  38. {
  39. if ( ( isRegisterName( args[1] ) && regs[static_cast<std::string>( args[1] )] )
  40. || ( !isRegisterName( args[1] ) && std::stoi( static_cast<std::string>( args[1] ) ) ) )
  41. {
  42. i += std::stoi( static_cast<std::string>( args[2] ) ) - 1;
  43. }
  44. }
  45. }
  46. return regs;
  47. }