0

I've been given a task/assigment to write a program that reads a c-like code (with specified syntax, so I dont need to worry about code in comments etc) and removes unnecessary calculations from inside the loop body to the outside. It can create new variables. Like in this example:

    Input:
for (i=1; i<100; i++)
{ b[i] = c[i] *a * 135.8; }
Output:
float __gen1 = a*135.8;
for (i=1; i<100; i++)
{ b[i] = c[i] *___gen1; }

I decided that the best aproach would be to run an 'optimize' recursive function, this way dealing with the nested loops would be easy. But how should I go about reading the code in the loop and deciding what to move out, and how to move it out outside the loop body?

I'm using C#.

Galik
  • 47,303
  • 4
  • 80
  • 117
  • If your assignment is making a compiler.. you might need a good parser library for C#. A start might be [this post](https://stackoverflow.com/a/2552225/4123703) – Louis Go May 27 '20 at 03:14
  • Why? Any decent compiler will already do this at one phase or another. You've been asked to write a good piece of a compiler here. This is a far from trivial task. Have you been given 3-5 months to do it in? – user207421 Jun 03 '20 at 04:11

1 Answers1

0

First you will need some way to create parse tree from the code. There are tools that let you build lexical analysers from the grammar of your c-like language. Which one you will use depends on the language you are implementing this in, if you are using java then you might want to use this: https://en.wikipedia.org/wiki/JavaCC

Once you have the tree, you can traverse it and look for expressions that are inside a loop and only use literals or variables that are not written inside the current loop. Those can be pulled out of the loop.

StefanFFM
  • 1,526
  • 1
  • 14
  • 25