dimanche 30 novembre 2014

JavaScript Language Parsing: Distinguish function expressions and declarations


Say that I am creating a simple JavaScript language parser that is only concerning with parsing functions.


I need to differentiate between function "declarations"/"statements" and function expressions. Because they look practically identical, I figure I need to know the context in which function is used.


I suppose that I can determine a function expression by the preceding token. I am thinking that the following algorithm might work:



  • If token is "function", then

    • If previous token is an operator,

      except for a "closing" operator, like "]", "}", or ")", OR

      if previous token is ":", then

      • Function is an function expression.



    • Else

      • Function is a function declaration.






Can I expect this algorithm to correctly determine if a function is a declaration or an expression? If it has flaws, what should be fixed? Or, if it is not possible to distinguish the forms simply by looking at the previous token, how else could I distinguish the forms with the least amount of effort?


(I am aware that Esprima and co. exist. I want to implement a native parser in a different language.)





Aucun commentaire:

Enregistrer un commentaire