lotabout / write-a-C-interpreter

Write a simple interpreter of C. Inspired by c4 and largely based on it.
GNU General Public License v2.0
4.04k stars 743 forks source link

Castom tokens #45

Open jenya7 opened 2 years ago

jenya7 commented 2 years ago

I have a simple, little script parser. For example to switch a sprinkler on time IF TIME == 12:00:00 THEN OUT1 = 1; IF TIME == 13:00:00 THEN OUT1 = 0; Or to activate some devices on environment condition. IF TEMP1 > 30.5 AND HUM2 > 60 THEN OUT2 = 1 Here I get a temperature of a sensor #1 and a humidity of a sensor #2. In my code it looks like ` switch (type) { case VAR_TYPE_TSENS: val = m_sensor.GetDataByValType(num, SENS_VAL_TYPE_TEMP); break;

case VAR_TYPE_HSENS: val = m_sensor.GetDataByValType(num, SENS_VAL_TYPE_HUM); break; } `

May I put it in the code?

` int eval() { int op, tmp; while (1) { op = pc++; // get next operation code

   //////////////////////////////////////////////////
    else if (op == MALC) { ax = (int)malloc(*sp);}
    else if (op == MSET) { ax = (int)memset((char *)sp[2], sp[1], *sp);}
    else if (op == MCMP) { ax = memcmp((char *)sp[2], (char *)sp[1], *sp);}

    ////////////// MY PART ///////////////////////////
    else if (op == TEMP)  { ax = m_sensor.GetDataByValType( num, SENS_VAL_TYPE_TEMP); }
    else if (op == HUM)  { ax = m_sensor.GetDataByValType( num, SENS_VAL_TYPE_HUM); }
}

}`

The question - how to parse my tokens (TEMP1, HUM2) and where to store the sensor's number (1,2)?

lotabout commented 2 years ago

What you want to achieve would require support for struct and switch which is beyond the scope of this project.

As for what you are trying to achieve is somehow in the wrong direction IMO: the op == ... part is actually the execution of the builtin virtual machine of xc. So all the user defined structs(e.g. TEMP1, HUM2 in your example) should not appear in the parser's code.

And according to your description, I think a production ready script language like lua or other good alternative would solve your problem quick and better.

jenya7 commented 2 years ago

LUA parser is pretty heavy for embedded applications.

How can I include in the script external functions? This way I could write ` int main() { int sens1_val; int sens2_val; while(1) { sens1_val = m_sensor.GetDataByValType(1, SENS_VAL_TYPE_TEMP); sens2_val = m_sensor.GetDataByValType(2, SENS_VAL_TYPE_HUM); if ( sens1_val > 30.5 && sens2_val > 60) Out(1, true);

}

} `