parse-asm-parse-gen.py 6.3 KB
Newer Older
1
#!/usr/bin/env python
Benoit Perrot's avatar
Benoit Perrot committed
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
##
## This file is part of Mipsy, a tiny MIPS simulator
## Copyright (C) 2003 Benoit Perrot <benoit@lrde.epita.fr>
##
## Mipsy is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
## 
## Mipsy is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
## GNU General Public License for more details.
## 
## You should have received a copy of the GNU General Public License
## along with this program; if not, write to the Free Software
## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
##
20
21
22
23
24

import sys
import string, re

import mipsy
Benoit Perrot's avatar
Benoit Perrot committed
25
from mipsy import license, depth, define_id
26

Benoit Perrot's avatar
Benoit Perrot committed
27
#### Mipsy's Bison assembly parser generator ---------------
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
parser = mipsy.InstructionSetParser()
instructions = parser.parse(sys.stdin)

## Prologue --------------------------
print "%{							// -*- C++ -*-"
print license
print """
#include <string>

#include \"common.hh\"

#include \"inst/label.hh\"
#include \"inst/program_builder.hh\"
#include \"inst/exp.hh\"
#include \"inst/register.hh\"
#include \"inst/all.hh\"

45
46
#include \"vm/cpu.hh\"

47
48
49
50
51
52
53
54
#include \"parse/libparse.hh\"

namespace yy
{
  extern inst::ProgramBuilder program_builder;
}

using namespace inst;
55
using vm::Cpu;
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
%}

%error-verbose
%locations
%debug

%union
{
  int			i;
  std::string		*s;
  inst::Label           *label;
  inst::Register        *reg;
  inst::Exp             *exp;
}
%{
#include \"parse/asm-scan.hh\"
%}

%token <label> LABEL		\"label\"
%token <label> LABEL_DEF	\"label definition\"
%token <i> INTEGER              \"integer\"
%token <s> STRING               \"string\"
%token <reg> REGISTER           \"register\"
%type <exp> exp

%token YYEOF		0 \"end of file\"
%token LPAREN		\"(\"
%token RPAREN		\")\"
%token COMMA		\",\"

%left EXP_ADD EXP_SUB
%left EXP_MUL EXP_DIV
%nonassoc EXP_UMINUS

%token DIR_TEXT         \".text\"
%token DIR_DATA         \".data\"
%token DIR_SPACE        \".space\"
%token DIR_WORD         \".word\"
%token DIR_ASCIIZ       \".asciiz\"
"""
  
for i in instructions:
  print "%token " + define_id(i.opcode) + '\t\t"' + i.opcode + '"'
  
print """
  
%start program
%%
// 
program
:
| program DIR_TEXT instructions
| program DIR_DATA datas


// Data definitions
datas
:
| datas data

data
// Label
:  LABEL_DEF
{ program_builder.add_data_label(* $1); }
// Reserve space
| DIR_SPACE INTEGER
{ program_builder.add_space ($2); }
// Values
| DIR_WORD INTEGER
{ program_builder.add_word ($2); }
| DIR_WORD LABEL
{ program_builder.add_word (*$2); }
| DIR_ASCIIZ STRING
{ program_builder.add_asciiz (* $2); }

// Instruction definitions
instructions
:
| instructions instruction

instruction
// Label
: LABEL_DEF
{ program_builder.add_inst_label(* $1); }

// Opcodes"""

Benoit Perrot's avatar
Benoit Perrot committed
143
144
145
## Body ------------------------------
tokid_map = {
  "register" : "REGISTER",
146
  "immediate": "exp",
Benoit Perrot's avatar
Benoit Perrot committed
147
148
149
  "label"    : "exp",
  "address"  : "REGISTER",
  "hidden"   : ""
150
151
  }

Benoit Perrot's avatar
Benoit Perrot committed
152

153
154
155
for inst in instructions:
  for syntax in inst.syntaxes:

Benoit Perrot's avatar
Benoit Perrot committed
156
157
158
159
160
161
162
163
164
    ## Compute productions
    # A token is a tuple (token id, token name, token value)
    prods = [[(define_id(inst.opcode), "", "")]]
    for i, token in enumerate(syntax.tokens):
      if token.kind == "address":
        prods.append([("LPAREN", "", "")])
      if token.default != "":
        prods.append([(tokid_map[token.kind], token.name, token.value),
                      ("", token.name, token.default)])
165
      else:
Benoit Perrot's avatar
Benoit Perrot committed
166
167
168
169
        prods.append([(tokid_map[token.kind], token.name, token.value)])
      if token.kind == "address":
        prods.append([("RPAREN", "", "")])
    prods = depth(prods)
170

Benoit Perrot's avatar
Benoit Perrot committed
171
    ## Display rules and actions
172
    for prod in prods:
Benoit Perrot's avatar
Benoit Perrot committed
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196

      # Add COMMAs
      tokidx = {}
      lparen_p = False
      i = 0
      while True:
        token = prod[i]
        if token[0] != "":
          if i > 1:
            if token[0] == "LPAREN":
              lparen_p = (prod[i - 1][0] != "")
            if not lparen_p:
              prod.insert(i, ("COMMA", "", ""))
              i = i + 1
          if token[0] == "LPAREN":
            lparen_p = True
          elif token[0] == "RPAREN":
            lparen_p = False
        i = i + 1
        if i >= len(prod):
          break
      
      # Compute token indices
      tokidx = {}
197
198
      i = 0
      for token in prod:
Benoit Perrot's avatar
Benoit Perrot committed
199
        if token[0] != "":
200
          i = i + 1
Benoit Perrot's avatar
Benoit Perrot committed
201
202
203
204
205
206
207
        if token[1] != "":
          assert(not tokidx.has_key(token[1]))
          tokidx[token[1]] = i
          
      # Build rule and action
      rule = "|"
      action = "program_builder.add_"
208
      if syntax.alias != "":
Benoit Perrot's avatar
Benoit Perrot committed
209
        action = action + syntax.alias + "("
210
      else:
Benoit Perrot's avatar
Benoit Perrot committed
211
        action = action + inst.opcode + "("
212
213
      i = 0
      for token in prod:
Benoit Perrot's avatar
Benoit Perrot committed
214
215
216
217
218
219
220
221
222
        if token[0] != "":
          i = i + 1
          rule = rule + " " + token[0]
        value = "*$" + str(i)
        if token[2] != "":
          value = re.sub(r"\$\{([^}]*)\}", 
                         (lambda m: "*$" + str(tokidx[m.groups(0)[0]])),
                         token[2])
        if token[0] in tokid_map.values():
223
224
          action = action + value + ", "
      action = string.rstrip(action, ", ") + ")"
Benoit Perrot's avatar
Benoit Perrot committed
225
226

      # Dump rule and associated action
227
      print rule
Benoit Perrot's avatar
Benoit Perrot committed
228
      print "{ " + action + "; }"
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274


## Epilogue --------------------------
print """
exp:
  exp EXP_ADD  exp { $$ = new OpExp(*$1, OpExp::add, *$3); }
| exp EXP_SUB  exp { $$ = new OpExp(*$1, OpExp::sub, *$3); }
| exp EXP_MUL  exp { $$ = new OpExp(*$1, OpExp::mul, *$3); }
| exp EXP_DIV  exp { $$ = new OpExp(*$1, OpExp::div, *$3); }
| EXP_SUB exp %prec EXP_UMINUS
        { $$ = new OpExp(*new IntExp(0), OpExp::sub, *$2); }
| LPAREN exp RPAREN { $$ = $2; }
| INTEGER { $$ = new IntExp($1); }
| LABEL { $$ = new LabelExp(*$1); }

%%
void
yy::Parser::error_ ()
{
  std::cerr << location << \": \" << message << std::endl;
  exit_set (exit_parse);
}

void
yy::Parser::print_ ()
{
  std::cerr << ' ' << location;
  switch (looka_)
    {
    case STRING:
      std::cerr << \": \" << *value.s;
      break;
    case INTEGER:
      std::cerr << \": \" << value.i;
      break;
    case REGISTER:
      std::cerr << \": \" << *value.reg;
      break;
    }
}

namespace yy
{
  inst::ProgramBuilder program_builder;
}
"""