1

I am trying to make a small interpreting program with JavaScript/jQuery. So what I want is that when the user enter some text in the textarea the program should interpret that text and print the output in another text area. Till now I have achieved this:

https://jsfiddle.net/7462hbv1/

With this I am able to catch each of the string that the user inputs in the text area. But now I want that when the user for example enter:

number a =1
number b=2
number sum=0
sum =a +b
print sum

the program should interpret this and the output should be 3 in this case. Can anyone give me any idea how can I do this? I am thinking of building a two dimensional array and save there each row (for each row to have type, name, value) and then make calculation with this array. I would appreciate any help. Thank you in advance

UPDATE

I have worked with my example and specifically with print statement. I have made it to print multiple strings or varibles(connected with +) and to print error message if + is missing. I have two problems now:

  1. I want to have a error message when try to print undefined variable and not output undefined like in this case( I want to have that messsage in the #errorstextarea):

    a = 240 b=120 print a + c the output is 240 undefined

  2. I want to have the character \iri instead '\n' for the print statement to go to new line. I have done this with var result2= result1.replace('\iri','\n'); but it does not function.

Here is my demo(DEMO)

Can you please help me?

UPDATE

I solve the second problem. Here is the DEMO. Can you please help me with the first one?

orsina
  • 131
  • 11
  • Why are you trying to reinvent the wheel? :-s The task is not that simple that it sounds.. – Mihai Matei Apr 24 '15 at 08:06
  • `eval` [link](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval) might get you somewhere. On the other hand: stack overflow isn't here to create the code for you, we are here to help you solve errors or specific problems. Please show us what you've tried and we'll see if we can improve it. Also, have a look at [this page](http://stackoverflow.com/help/how-to-ask) – Jordumus Apr 24 '15 at 08:09
  • Matei proabably means that there is already a library doing this. If you want to do it yourself then you need to parse the expression (build the tree) and calculate the result from bottom to top. – maraca Apr 24 '15 at 08:09
  • I know that it is not simple, but I am trying to make a simple interpreter in my own language, but for simplicity I have written the instruction and keywords there in English. Can you give me any hint? – orsina Apr 24 '15 at 08:11
  • Implementing interpreter is not an easy task.. Also it's not efficient for large statements. Why do you need to do that ? Also you're not using javascript semantics of variables, you need to map your instructions to JS instructions which is a tedious job on its own :) – Arkantos Apr 24 '15 at 08:12
  • @Arkantos I am trying to do that for better understanding how interpreters work. I am doing this for educational purpose and to do simple interpreting task in my own language. Can you give me any advice where to start? – orsina Apr 24 '15 at 08:18
  • My answer was how to parse mathematical formulas, if you really want to build an interpreter then you first have to start with the language design. It's easiest to write an interpreter if you don't need to look ahead when parsing. Then when you've build the tree of statements you have to resolve variable names and functions etc. and then you have to translate it to another language or produce machine code... – maraca Apr 24 '15 at 08:19
  • @maraca can you give me any hint how can I parse the expression? And suggestion reading for this? – orsina Apr 24 '15 at 08:20
  • Are the instructions fixed? before parsing that I think your first approach should be how to restrict users from entering junk and handle indents and spacing. So if user types PRINT 'Get Lost' your program should say Please stay – Girish Sakhare Apr 24 '15 at 08:20
  • @GirishSakhare no they are not fixed. But what can I use to restrict users from entering junk intents? – orsina Apr 24 '15 at 08:22
  • @orsina How does the instruction set look like, e.g. you have only variable assignment, print and mathematical formulas? – maraca Apr 24 '15 at 08:24
  • I really need any hint, suggestion or any point to start from you. I am not asking to make the code for me. I am not sure what way to follow for solving this... – orsina Apr 24 '15 at 08:24
  • On key press validate the character to make sure if its a operator then add extra space, if character check if previous word or character is a keyword or a variable etc etc, hell lots of if else. First you think or draft what all keywords user can use, what sort of validations you want to provide and what are the limitations. – Girish Sakhare Apr 24 '15 at 08:26
  • Even in your own language, you have to layout some rules saying what is allowed and what isn't :) An interpreter is nothing but a big while loop reading one line at a time from the source code and executing it. But if you're trying to implement the whole thing on your own, there are so many layers you need to create to finally translate the code written in your own language to assembly instructions understood by the machine on which you're running code, then feed those instructions to the CPU to do the actual work :) – Arkantos Apr 24 '15 at 08:32
  • @GirishSakhare yes this is what I have think to do. First to build a syntax of my simple "language". I understand now what you mean. Butt I decided to ask this question now(before deciding the syntax) in order to know for example for a simple case like about, what logic should I follow. (for example if I have only the keywords above). Thank you for your time and help – orsina Apr 24 '15 at 08:32
  • Instead of you trying to implement an interpreter, I suggest you try to understand existing interpreters in java/python/scala or any language you find easy to understand and when it makes sense to you, you can try to create your own :) – Arkantos Apr 24 '15 at 08:34
  • jsFiddle is your benchmark. http://davidwalsh.name/jsfiddle-interview @orsina i am not underestimating your skills, however you are trying something that I am not sure what benefits you will get from it? Even if you make an interpreter but the way you will make it has to be validated by experts. And as Arkantos said its good to study existing once and learn what they went through the problems and what extra you can provide. Other than that you can keep experimenting side by side though not fulltime – Girish Sakhare Apr 24 '15 at 08:38
  • @GirishSakhare thanks for your advice. And the last could you suggest me any opensource interpreter in python? I am working with python now and it will be easy for me to understand it and than try to build my own. – orsina Apr 24 '15 at 08:51
  • added working example – maraca Apr 24 '15 at 22:58

1 Answers1

2

This is not how compilers / interpreters are written, but it should do for an easy language:

  1. Define regular expressions for each statement (e.g. if you only allow to print variables /^print ([a-z]+)$/).

  2. Match each line against the expressions and decide what to do (e.g. if you translate to javascript your print statement could become $('#output').append(variablename + '<br>'); and mathematical formulas don't need to be translated at all, just validated).

  3. If everything is correct execute script. Possible problems: overwriting system variables or variables named like keywords (→ prefix your variables in the generated code or store them all in the same array / object), script injection (→ escape ' in your strings (\') and replace < and > with &lt; and &gt; and possibly other restrictions).

Here is a very simple example calculating the greatest common divisor:

https://jsfiddle.net/7462hbv1/6/

Some remarks:

  1. It's a pretty stupid language but I think it is Turing complete.
  2. There should be various checks (e.g. only the individual lines are checked, not if an if is correctly closed) and meaningful error messages.
  3. Only one datatype is supported: integer
  4. Variable names can have lower and upper case letters but nothing else
  5. grammar (incomplete):

    <int> ::= 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9
    <integer> ::= <int>[<int>*]
    <assignment> ::= <variable> = <formula>
    <value> ::= <integer> | <variable>
    <formula> ::= [<formulaPart>*] <value>
    <operator> ::= + | - | * | / | %
    <formulaPart> ::= <value> <operator>
    <while> ::= while <variable>
    <endWhile> ::= end while
    <comparator> ::= > | < | =
    <if> ::= if <variable> <comparator> <value>
    <else> ::= else
    <endIf> ::= end if
    <print> ::= print "<message>" [<variable>]
    

    Note that there are no brackets, you have to split the lines of code until your math needs no more brackets.

  6. Here is how the (working!) GCD program looks like in this language:

    print "Euclidean algorithm"
    a = 240
    print "a = " a
    b = 360
    print "b = " b
    if a > 0
      while b
        if a > b
          a = a - b
        else
          b = b - a
        end if
      end while
      print "gcd: " a
    else
      print "gcd: " b
    end if
    
  7. And this is the code actually executed:

    myProgram=function(){var variables=[];var pOut='';pOut+='Euclidean algorithm\n';variables['a']=240;pOut+='a = '+variables['a']+'\n';variables['b']=360;pOut+='b = '+variables['b']+'\n';if(variables['a']>0){while(variables['b']){if(variables['a']>variables['b']){variables['a']=variables['a']-variables['b'];}else{variables['b']=variables['b']-variables['a'];}}pOut+='gcd: '+variables['a']+'\n';}else{pOut+='gcd: '+variables['b']+'\n';}$('#output').html(pOut);};myProgram();
    
maraca
  • 8,468
  • 3
  • 23
  • 45
  • Thanks maraca. I am trying this to structure my code. Can I ask you for any suggestion material where I can improve my knowledge on Regular Expression on JavaScript? – orsina Apr 24 '15 at 08:55
  • 1
    A great website to play with and learn regular expressions: http://www.regexr.com/ – Nicolas Le Thierry d'Ennequin Apr 24 '15 at 08:57
  • In fact I dot have any great experience with them, just some small tasks I have done. Thanks, I will try to really achieve this – orsina Apr 24 '15 at 09:01
  • @orsina added some more information, thanks for accepting, I can't stress how careful you have to be or someone is going to do bad stuff if he can. – maraca Apr 24 '15 at 09:20
  • @maraca thanks a lot. You really helped me. I am working on defining the grammar now and than build an executable example...Thanks a lot again :) – orsina Apr 25 '15 at 11:24
  • @orsina you're welcome, just noticed that when comparing you would have to replace = by ==. I was asking myself something similar, so no problem ;-) – maraca Apr 25 '15 at 11:33
  • Hi @maraca! Can you please help me? The part that is confusing me is: s += "pOut+='" + replaceAll({string: t[1], search: "'", replace: "\\'"}) + (typeof t[3] == 'undefined' ? "\\n'" : "'+variables['" + t[3] + "']+'\\n'") + ";";. I dont understand what value take search in that case and what is the purpose of function replaceAll? Thanks in advance – orsina Apr 29 '15 at 19:04
  • @orsina ok, 1st thing I didn't mention: if you do the output like this, then it will only be printed in the end. if you want to have it live then you have do it with append like explained on top. 2nd you will have to not only replace `'` by `\\'` (this is what the function does, escaping `'` for the output), to be safe you will also have to replace `<` and `>` with `<` and `>` but I was too lazy. – maraca Apr 29 '15 at 19:22
  • @macara sorry for my question and thanks for your support. I try now with `'` and it really escape it. In fact I confuse it with the values included at the first function. I will also add the other replacement you suggest and work with append. Thanks again:) – orsina Apr 29 '15 at 19:32
  • @maraca I am working with my example and i have a problem right now. Could you please help me? Thanks in advance for all your help – orsina May 03 '15 at 16:48
  • @orsina it depends, what the problem is. Anyway you can just open a new question, it's the easiest way to help. – maraca May 03 '15 at 20:24
  • @maraca sorry bur I forget to menioned that I update my question above. Anyway I solved both of my problems. For the second one I publish the answer above, but I just solved the first too. Thanks again for your availability to help:) – orsina May 03 '15 at 21:39
  • @maraca can you help me with my problem. I am trying to implement the read function(equivalent of cin in c++). I have published my problem here [link](http://stackoverflow.com/questions/30134529/how-to-return-value-from-jquery-function/30134563#30134563) and a small version of my demo is here(line 93)[link](https://jsfiddle.net/orsina/k9e4nhnw/3/). My problem is that the value from read function that i add to `s` is entered at the and of `s` not inside `myProgram()`. I really really thank you... – orsina May 09 '15 at 00:45