We have defined types:

 

type position = {line : int; col : int };;

type 'a ast = {data : 'a; kids : 'a ast list; posf : position; post: position};;

 

 

And then we transform string to ast:

 

let construct_common_ast s=

    let len = String.length s in

    let rec aux i j=

      if i>j then []

      else (

        let k = find_first s "(,)" i in

        let str = trim (String.sub s i (k-i)) in

        if k>j || s.[k]=')' then (

          if str="" then []

          else {data=str; kids=[]; posf=(calc_pos s i); post=(calc_pos s j)}::[]

        )

        else if s.[k]='(' then (

          let l = next_matched s '(' ')' (k+1) in

          let m = find_first_not s " \t\n\r" (l+1) in

          if m<=j && s.[m]<>',' then

              fail_ast (calc_pos s k) (calc_pos s l) "construct_common_ast: invalid input string"

          else

              {data=str; kids=aux (k+1) (l-1); posf=(calc_pos s i); post=(calc_pos s l)} :: aux (m+1) j

        )

        else {data=str; kids=[]; posf=(calc_pos s i); post=(calc_pos s k)} :: aux (k+1) j

      )

    in

    let trees=aux 0 (len-1) in

List.hd trees;;

 

For construct_common_ast :

# construct_common_ast;;

- : string -> string ast = <fun>

# construct_common_ast "node (function, params(), returns())";;

- : string ast =

{data = "node";

 kids =

  [{data = "function"; kids = []; posf = {line = 1; col = 8};

    post = {line = 1; col = 16}};

   {data = "params"; kids = []; posf = {line = 1; col = 17};

    post = {line = 1; col = 25}};

   {data = "returns"; kids = []; posf = {line = 1; col = 27};

    post = {line = 1; col = 36}}];

 posf = {line = 1; col = 2}; post = {line = 1; col = 37}}.

 

But, it is intolerable to deal with long string. how to increase coding efficiency of this function?

 

Thank you anyway.

Best wishes!