22
$\begingroup$

Background

Usually, I give detailed descriptions when I have a question which sometimes lead to that users don't write their answers because they maybe think their answer is too simple. Therefore, I chose to just throw the direct question in the room and collect the ideas of all answers.

Although it seems, that we cannot get a simple tokenizer by using functions like TreeForm, MakeBoxes, MakeExpression, ... I want to give some background information now:

What really bothers me is, that we have here on Mathematica.SE a highlighter for Mathematica code which is far away from perfect, but which does a reasonable job. If I want to include a snippet of code into a LaTeX document on the other hand, I'm totally stuck with a b/w-pdf export from Mathematica or with the Mathematica 5.2 support of the listings package.

Therefore, I hacked a simple parser of the html-output of our google-prettify plugin. This seems to work reasonable and with a little bit adjustment, one could include styled Mathematica-code into a LaTeX document. It should be noted, that I don't intent to export formulas or sophisticated styled code. I want to stick with good old ascii-style code which is used in most packages.

Before I used the html-output I was again having a long look at Leonids formatter but at its current state it lacks of the same issues since it relies on MakeBoxes as well and there are other issues. Leonid pointed out, that he want to reimplement this completely.

On the other hand, we have functions like SyntaxLength, SyntaxQ, MakeExpression, MakeBoxes (and their To counterparts), all kind of Forms, we can keep expressions unevaluated and so on. Therefore, I was asking myself whether we can do the tokenizing much easier with Mathematica that it is possible with the JavaScript from google-prettify.

Question

Is it possible to implement a reliable tokenizer which takes a valid input-string of Mathematica code and returns a list of tokens without implementing the rules of the Mathematica-language itself?

Although tokens usually don't contain whitespace characters, for the purpose of testing it would be nice, if all characters stay even in the tokenized version.

Especially I want

input == StringJoin@@Tokenize[input]

to return True.

Take for instance this function

Tokenize[str_String /; SyntaxQ[str]] := 
  With[{expr = MakeExpression[str, StandardForm]},
   Most[Drop[Flatten[MakeBoxes[expr] /. {
        RowBox -> List, SuperscriptBox[a_, b_] :> {a, "^", b}, 
        "\[Rule]" :> "->"}], 2]]
];

Tokenize[
"Plot3D[{x^2+y^2,-x^2-y^2},{x,-2,2},{y,-2,2},RegionFunction->Function[{x,y,z},x^2+y^2<=4]]"
]
(*
 {"Plot3D", "[", "{", "x", "^", "2", "+", "y", "^", "2", ",", 
 "-", "x", "^", "2", "-", "y", "^", "2", "}", ",", "{", "x", 
 ",", "-", "2", ",", "2", "}", ",", "{", "y", ",", "-", "2", 
 ",", "2", "}", ",", "RegionFunction", "->", 
 "Function", "[", "{", "x", ",", "y", ",", "z", "}", ",", "x", 
 "^", "2", "+", "y", "^", "2", "<=", "4", "]", "]"}
*)

Although the output looks good here, inside Mathematica we have \[LessEqual] instead of <= (due to the StandardForm I assume). Furthermore, all different kind boxes need to be handled and I'm afraid many more things.

Is there any chance to get this working really correctly?

Test examples:

In some of these cases I'm not sure whether my given output is the correct one. E.g. the handling of linebreaks may be system-dependent, a_ seems to stay together in the box-representation (which would be ok), ...

"a\nb" (* {"a","\n","b"} *)
"a_:>a/2<=3" (* {"a_",":>","a","/","2","<=","3"} *)
"1`3+1.00`3" (* I'm not sure how this should be tokenized but my intention should be clear *)
$\endgroup$
2
  • $\begingroup$ What can you say about the input? What if it has string representation of boxes, how would you want the output? $\endgroup$
    – Rojo
    Oct 16, 2012 at 1:37
  • $\begingroup$ @Rojo I updated my question with additional information. You can assume that the code I want to tokenize is simple ascii-code like it is used on our site here. $\endgroup$
    – halirutan
    Oct 17, 2012 at 1:19

3 Answers 3

14
$\begingroup$
tokenize[str_] := Module[{exp,
   nb = CreateDocument[{ExpressionCell@
       InputForm@MakeExpression[str, StandardForm]}, 
     Visible -> False]},
  SelectionMove[nb, Next, Cell];
  exp = Flatten[
    NotebookRead[nb][[1, 1]] /. {RowBox -> List, 
      i_String /; StringMatchQ[i, Whitespace ..] :> Sequence[]}];
  NotebookClose[nb];
  exp[[3 ;;-2]]
  ]

Haven't tested this much. Does this give the output you expect?

tokenize["Plot3D[{x^2+y^2,-x^2-y^2},{x,-2,2},{y,-2,2},\
RegionFunction->Function[{x,y,z},x^2+y^2<=4]]"]

(*{"Plot3D","[","{","x","^","2","+","y","^","2",",","-","x","^","2","-\
","y","^","2","}",",","{","x",",","-","2",",","2","}",",","{","y",",",\
"-","2",",","2","}",",","RegionFunction","->","Function","[","{","x",\
",","y",",","z","}",",","x","^","2","+","y","^","2","<=","4","]","]",\
"]"}*)

EDIT

Thanks to @JohnFultz's recent introduction of the following front end undocumented function, this becomes straightforward

 fultzTokenize[t_String]:=Cases[MathLink`CallFrontEnd[
   FrontEnd`UndocumentedTestFEParserPacket[t, False]], _String, Infinity]
$\endgroup$
8
  • $\begingroup$ The idea is good! Don't remove whitespace, because I want input == StringJoin@@tokenize[input] to return true; see my update. Your function adds a ] to the tokens at the end: tokenize["a+b"] $\endgroup$
    – halirutan
    Oct 15, 2012 at 22:17
  • $\begingroup$ @halirutan, with this approach you could only make input==StringJoin... if you can offer certain guarantees on the input's format. Otherwise, a manual approach, working on the strings, splitting them, is probably the only way I guess. Fixed the extra "]", thanks $\endgroup$
    – Rojo
    Oct 15, 2012 at 22:33
  • $\begingroup$ aah! You beat me to stealing the Futz! $\endgroup$
    – rm -rf
    Oct 21, 2012 at 0:09
  • 1
    $\begingroup$ @Rojo, Shame on you both. You could have at least noticed, that his name is Fultz when you are stealing his code ;-) $\endgroup$
    – halirutan
    Oct 21, 2012 at 2:32
  • 5
    $\begingroup$ Well, if you're going to steal from "the Futz" (my new nickname?), you could at least tighten up the code. Instead of the DeleteCases you have, how about Cases[#,_String,Infinity]&? And...the question was specified (in boldface, even) as wanting whitespace not to be stripped. In which case the second argument to UndocumentedTestFEParserPacket should be False, not True. $\endgroup$
    – John Fultz
    Oct 21, 2012 at 3:45
13
$\begingroup$

I am a developer at Wolfram Research and I am trying to share some of the work I have been doing with parsing WL code.

I have written a package for parsing WL code and retaining interesting metadata, such as file and line information.

I also expose a tokenization function.

The paclet is available on the public paclet server:

In[1]:= PacletUpdate["AST","Site"->"http://pacletserver.wolfram.com","UpdateSites"->True]
Out[1]= Paclet[AST,0.8.1,<>]

Load the AST package:

Needs["AST`"]

The AST package has a function TokenizeString that returns a list of tokens when it is given WL input:

In[2]:= TokenizeString["Plot3D[{x^2+y^2,-x^2-y^2},{x,-2,2},{y,-2,2},RegionFunction->Function[{x,y,z},x^2+y^2<=4]]"]
Out[2]= {Token[Token`Symbol,Plot3D,<|Source->{{1,1},{1,6}}|>],
Token[Token`Operator`OpenSquare,[,<|Source->{{1,7},{1,7}}|>],
Token[Token`Operator`OpenCurly,{,<|Source->{{1,8},{1,8}}|>],
Token[Token`Symbol,x,<|Source->{{1,9},{1,9}}|>],
Token[Token`Operator`Caret,^,<|Source->{{1,10},{1,10}}|>],
Token[Token`Number,2,<|Source->{{1,11},{1,11}}|>],
Token[Token`Operator`Plus,+,<|Source->{{1,12},{1,12}}|>],
Token[Token`Symbol,y,<|Source->{{1,13},{1,13}}|>],
Token[Token`Operator`Caret,^,<|Source->{{1,14},{1,14}}|>],
Token[Token`Number,2,<|Source->{{1,15},{1,15}}|>],
Token[Token`Operator`Comma,,,<|Source->{{1,16},{1,16}}|>],
Token[Token`Operator`Minus,-,<|Source->{{1,17},{1,17}}|>],
Token[Token`Symbol,x,<|Source->{{1,18},{1,18}}|>],
Token[Token`Operator`Caret,^,<|Source->{{1,19},{1,19}}|>],
Token[Token`Number,2,<|Source->{{1,20},{1,20}}|>],
Token[Token`Operator`Minus,-,<|Source->{{1,21},{1,21}}|>],
Token[Token`Symbol,y,<|Source->{{1,22},{1,22}}|>],
Token[Token`Operator`Caret,^,<|Source->{{1,23},{1,23}}|>],
Token[Token`Number,2,<|Source->{{1,24},{1,24}}|>],
Token[Token`Operator`CloseCurly,},<|Source->{{1,25},{1,25}}|>],
Token[Token`Operator`Comma,,,<|Source->{{1,26},{1,26}}|>],
Token[Token`Operator`OpenCurly,{,<|Source->{{1,27},{1,27}}|>],
Token[Token`Symbol,x,<|Source->{{1,28},{1,28}}|>],
Token[Token`Operator`Comma,,,<|Source->{{1,29},{1,29}}|>],
Token[Token`Operator`Minus,-,<|Source->{{1,30},{1,30}}|>],
Token[Token`Number,2,<|Source->{{1,31},{1,31}}|>],
Token[Token`Operator`Comma,,,<|Source->{{1,32},{1,32}}|>],
Token[Token`Number,2,<|Source->{{1,33},{1,33}}|>],
Token[Token`Operator`CloseCurly,},<|Source->{{1,34},{1,34}}|>],
Token[Token`Operator`Comma,,,<|Source->{{1,35},{1,35}}|>],
Token[Token`Operator`OpenCurly,{,<|Source->{{1,36},{1,36}}|>],
Token[Token`Symbol,y,<|Source->{{1,37},{1,37}}|>],
Token[Token`Operator`Comma,,,<|Source->{{1,38},{1,38}}|>],
Token[Token`Operator`Minus,-,<|Source->{{1,39},{1,39}}|>],
Token[Token`Number,2,<|Source->{{1,40},{1,40}}|>],
Token[Token`Operator`Comma,,,<|Source->{{1,41},{1,41}}|>],
Token[Token`Number,2,<|Source->{{1,42},{1,42}}|>],
Token[Token`Operator`CloseCurly,},<|Source->{{1,43},{1,43}}|>],
Token[Token`Operator`Comma,,,<|Source->{{1,44},{1,44}}|>],
Token[Token`Symbol,RegionFunction,<|Source->{{1,45},{1,58}}|>],
Token[Token`Operator`MinusGreater,->,<|Source->{{1,59},{1,60}}|>],
Token[Token`Symbol,Function,<|Source->{{1,61},{1,68}}|>],
Token[Token`Operator`OpenSquare,[,<|Source->{{1,69},{1,69}}|>],
Token[Token`Operator`OpenCurly,{,<|Source->{{1,70},{1,70}}|>],
Token[Token`Symbol,x,<|Source->{{1,71},{1,71}}|>],
Token[Token`Operator`Comma,,,<|Source->{{1,72},{1,72}}|>],
Token[Token`Symbol,y,<|Source->{{1,73},{1,73}}|>],
Token[Token`Operator`Comma,,,<|Source->{{1,74},{1,74}}|>],
Token[Token`Symbol,z,<|Source->{{1,75},{1,75}}|>],
Token[Token`Operator`CloseCurly,},<|Source->{{1,76},{1,76}}|>],
Token[Token`Operator`Comma,,,<|Source->{{1,77},{1,77}}|>],
Token[Token`Symbol,x,<|Source->{{1,78},{1,78}}|>],
Token[Token`Operator`Caret,^,<|Source->{{1,79},{1,79}}|>],
Token[Token`Number,2,<|Source->{{1,80},{1,80}}|>],
Token[Token`Operator`Plus,+,<|Source->{{1,81},{1,81}}|>],
Token[Token`Symbol,y,<|Source->{{1,82},{1,82}}|>],
Token[Token`Operator`Caret,^,<|Source->{{1,83},{1,83}}|>],
Token[Token`Number,2,<|Source->{{1,84},{1,84}}|>],
Token[Token`Operator`LessEqual,<=,<|Source->{{1,85},{1,86}}|>],
Token[Token`Number,4,<|Source->{{1,87},{1,87}}|>],
Token[Token`Operator`CloseSquare,],<|Source->{{1,88},{1,88}}|>],
Token[Token`Operator`CloseSquare,],<|Source->{{1,89},{1,89}}|>],
Token[Token`EOF,,<|Source->{{2,0},{2,0}}|>]}

The AST paclet is under development and the format of the output may change, but hopefully this can help.

$\endgroup$
4
$\begingroup$

This, with a suitable transform function to traverse the tree, would be an adequate tokenizer:

TreeForm[Hold[
  Plot3D[{x^2 + y^2, -x^2 - y^2}, {x, -2, 2}, {y, -2, 2}, 
   RegionFunction -> Function[{x, y, z}, x^2 + y^2 <= 4]]]]

Mathematica graphics

$\endgroup$
4
  • 2
    $\begingroup$ No, I don't think the input can be reconstructed from that. Mathematica did already too much work: compare TreeForm[1`3] and TreeForm[1.00`3]. $\endgroup$
    – halirutan
    Oct 16, 2012 at 0:02
  • $\begingroup$ You can of course wrap some Hold around the numeric value, but the outcome stays the same. $\endgroup$
    – halirutan
    Oct 16, 2012 at 0:27
  • $\begingroup$ @halirutan Good counter example :) Maybe this case, and perhaps others, needs the application of a pre-processor. If I've used it correctly I don't think tokenize from rojo's solution distinguishes between the two forms you give in your example either. $\endgroup$ Oct 16, 2012 at 7:29
  • $\begingroup$ Yes, Rojos tokenize lacks from the same problem. I added more information to my question. $\endgroup$
    – halirutan
    Oct 17, 2012 at 1:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.