123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301(* Yoann Padioleau
*
* Copyright (C) 2013 Facebook
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* version 2.1 as published by the Free Software Foundation, with the
* special exception on linking described in file license.txt.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the file
* license.txt for more details.
*)openCommon(*****************************************************************************)(* Prelude *)(*****************************************************************************)(*
* When searching for or refactoring code, regexps are good enough most of
* the time; tools such as 'grep' or 'sed' are great. But certain regexps
* are tedious to write when one needs to handle variations in spacing,
* the possibilty to have comments in the middle of the code you
* are looking for, or newlines. Things are even more complicated when
* you want to handle nested parenthesized expressions or statements. This is
* because regexps can't count. For instance how would you
* remove a namespace in C++? You would like to write a transformation
* like:
*
* - namespace my_namespace {
* ...
* - }
*
* but regexps can't do that[1].
*
* The alternative is then to use more precise tools such as 'sgrep'
* or 'spatch'. But implementing sgrep/spatch in the usual way
* for a new language, by matching AST against AST, can be really tedious.
* The AST can be big and even if we can auto generate most of the
* boilerplate code, this still takes quite some effort (see lang_php/matcher).
*
* Moreover, in my experience matching AST against AST lacks
* flexibility sometimes. For instance many people want to use 'sgrep' to
* find a method foo and so do "sgrep -e 'foo(...)'" but
* because the matching is done at the AST level, 'foo(...)' is
* parsed as a function call, not a method call, and so it will
* not work. But people expect it to work because it works
* with regexps. So 'sgrep' for PHP currently forces people to write this
* pattern '$V->foo(...)'.
* In the same way a pattern like '1' was originally matching
* only expressions, but was not matching static constants because
* again it was a different AST constructor. Actually many
* of the extensions and bugfixes in sgrep_php/spatch_php in
* the last year has been related to this lack of flexibility
* because the AST was too precise.
*
* Enter Ast_fuzzy, a way to factorize most of the needs of
* 'sgrep' and 'spatch' over different programming languages,
* while being more flexible in some ways than having a precise AST.
* It fills a niche between regexps and very-precise ASTs.
*
* In Ast_fuzzy we just want to keep the parenthesized information
* from the code, and abstract away spacing, the main things that
* regexps have troubles with, and then let people match over this
* parenthesized cleaned-up tree in a flexible way.
*
* related:
* - xpath? but do programming languages need the full power of xpath?
* usually an AST just have 3 different kinds of nodes, Defs, Stmts,
* and Exprs.
*
* See also lang_cpp/parsing_cpp/test_parsing_cpp and its parse_cpp_fuzzy()
* and dump_cpp_fuzzy() functions. Most of the code related to Ast_fuzzy
* is in matcher/ and called from 'sgrep' and 'spatch'.
* For 'sgrep' and 'spatch' examples, see unit_matcher.ml as well as
* tests/cpp/sgrep/ and tests/cpp/spatch/
*
* notes:
* [1] Actually Perl regexps are more powerful so one can do for instance:
* echo 'something< namespace<x<y<z,t>>>, other >' |
* perl -pe 's/namespace(<(?:[^<>]|(?1))*>)/foo/'
* => 'something< foo, other >'
* but it's arguably more complicated than the proposed spatch above.
*
* todo:
* - handle infix operators: parse them not as a sequence
* but as a tree as we want for instance '$X->foo()' to match
* whole expression like 'this->bar()->foo()', or we want
* '$X' to match '1+1' (and not only in Parens context)
* - same for function calls? so maybe we need to transform our
* original program in a lisp like AST where things are more uniform
* - how to handle isomorphisms like 'order of attributes don't matter'
* as in XHP? or class that can be mentioned anywhere in the arguments
* to implements? or how can we make 'class X { ... }' to also match
* 'class X extends whatever { ... }'? or have public/static to
* be optional?
* Use regexp over trees? Use isomorphisms file as in coccinelle?
* Have special mark about optional things in ast_fuzzy?
* Derives such information from the grammar?
* - want powerful queries like
* 'class X { ... function(...) { ... foo() ... } ... }
* so sgrep powerful for microlevel queries, and prolog for macrolevel
* queries. Xpath? Css selector?
*)(*****************************************************************************)(* Types *)(*****************************************************************************)typetok=Parse_info.infotype'awrap='a*toktypetree=(* todo: comma *)|Parensoftok*(trees,tok(* comma*))Common.eitherlist*tok|Bracesoftok*trees*tok|Angleoftok*trees*tok|Bracketoftok*trees*tok(* note that gcc allows $ in identifiers, so using $ for metavariables
* means we will not be able to match such identifiers. No big deal.
*)|Metavarofstringwrap(* note that "..." are allowed in many languages, so using "..."
* to represent a list of anything means we will not be able to
* match specifically "...".
*)|Dotsoftok|Tokofstringwrapandtrees=treelist(* with tarzan *)letis_metavars=s=~"^\\$.*"(*****************************************************************************)(* Visitor *)(*****************************************************************************)typevisitor_out=trees->unittypevisitor_in={ktree:(tree->unit)*visitor_out->tree->unit;ktrees:(trees->unit)*visitor_out->trees->unit;ktok:(tok->unit)*visitor_out->tok->unit;}let(default_visitor:visitor_in)={ktree=(fun(k,_)x->kx);ktok=(fun(k,_)x->kx);ktrees=(fun(k,_)x->kx);}let(mk_visitor:visitor_in->visitor_out)=funvin->letrecv_treex=letkx=matchxwith|Braces((v1,v2,v3))->let_v1=v_tokv1and_v2=v_treesv2and_v3=v_tokv3in()|Parens((v1,v2,v3))->let_v1=v_tokv1and_v2=Ocaml.v_list(Ocaml.v_eitherv_treesv_tok)v2and_v3=v_tokv3in()|Angle((v1,v2,v3))->let_v1=v_tokv1and_v2=v_treesv2and_v3=v_tokv3in()|Bracket((v1,v2,v3))->let_v1=v_tokv1and_v2=v_treesv2and_v3=v_tokv3in()|Metavarv1->let_v1=v_wrapv1in()|Dotsv1->let_v1=v_tokv1in()|Tokv1->let_v1=v_wrapv1in()invin.ktree(k,all_functions)xandv_treesa=letkxs=matchxswith|[]->()|x::xs->v_treex;v_treesxs;invin.ktrees(k,all_functions)aandv_wrap(_s,x)=v_tokxandv_tokx=letk_x=()invin.ktok(k,all_functions)xandall_functionsx=v_treesxinall_functions(*****************************************************************************)(* Map *)(*****************************************************************************)typemap_visitor={mtok:(tok->tok)->tok->tok;}let(mk_mapper:map_visitor->(trees->trees))=funhook->letrecmap_tree=function|Braces((v1,v2,v3))->letv1=map_tokv1andv2=map_treesv2andv3=map_tokv3inBraces((v1,v2,v3))|Parens((v1,v2,v3))->letv1=map_tokv1andv2=List.map(Ocaml.map_of_eithermap_treesmap_tok)v2andv3=map_tokv3inParens((v1,v2,v3))|Angle((v1,v2,v3))->letv1=map_tokv1andv2=map_treesv2andv3=map_tokv3inAngle((v1,v2,v3))|Bracket((v1,v2,v3))->letv1=map_tokv1andv2=map_treesv2andv3=map_tokv3inBracket((v1,v2,v3))|Metavarv1->letv1=map_wrapv1inMetavar((v1))|Dotsv1->letv1=map_tokv1inDots((v1))|Tokv1->letv1=map_wrapv1inTok((v1))andmap_treesv=List.mapmap_treevandmap_tokv=letkv=vinhook.mtokkvandmap_wrap(s,t)=(s,map_tokt)inmap_trees(*****************************************************************************)(* Extractor *)(*****************************************************************************)let(toks_of_trees:trees->Parse_info.infolist)=funtrees->letglobals=ref[]inlethooks={default_visitorwithktok=(fun(_k,_)i->Common.pushiglobals)}inbeginletvout=mk_visitorhooksinvouttrees;List.rev!globalsend(*****************************************************************************)(* Abstract position *)(*****************************************************************************)letabstract_position_treestrees=lethooks={mtok=(fun(_k)i->{iwithParse_info.token=Parse_info.Ab})}inletmapper=mk_mapperhooksinmappertrees(*****************************************************************************)(* Vof *)(*****************************************************************************)letvof_tokent=Ocaml.VString(Parse_info.str_of_infot)(* Parse_info.vof_token t*)letrecvof_multi_grouped=function|Braces((v1,v2,v3))->letv1=vof_tokenv1andv2=Ocaml.vof_listvof_multi_groupedv2andv3=vof_tokenv3inOcaml.VSum(("Braces",[v1;v2;v3]))|Parens((v1,v2,v3))->letv1=vof_tokenv1andv2=Ocaml.vof_list(Ocaml.vof_eithervof_treesvof_token)v2andv3=vof_tokenv3inOcaml.VSum(("Parens",[v1;v2;v3]))|Angle((v1,v2,v3))->letv1=vof_tokenv1andv2=Ocaml.vof_listvof_multi_groupedv2andv3=vof_tokenv3inOcaml.VSum(("Angle",[v1;v2;v3]))|Bracket((v1,v2,v3))->letv1=vof_tokenv1andv2=Ocaml.vof_listvof_multi_groupedv2andv3=vof_tokenv3inOcaml.VSum(("Bracket",[v1;v2;v3]))|Metavarv1->letv1=vof_wrapv1inOcaml.VSum(("Metavar",[v1]))|Dotsv1->letv1=vof_tokenv1inOcaml.VSum(("Dots",[v1]))|Tokv1->letv1=vof_wrapv1inOcaml.VSum(("Tok",[v1]))andvof_wrap(s,_x)=Ocaml.VStringsandvof_treesxs=Ocaml.VList(xs+>List.mapvof_multi_grouped)