« Ocaml | トップページ | iPad »

2010年2月 2日 (火)

OCamlでパース

実家にPCを持って帰ってOcamlでのパースの続きをしようとしたところ、
ACアダプターを忘れて手をつけられず。ちょっと勢いが落ちた・・・

軽く調べた限りではOcamlではCamlp4というプリプロセッサを使って自分自身の構文を拡張する?機能があるらしく、その機能を使うとパーサーを作れるのかな?
http://www.jmuk.org/~mukai/camlp4tut.html (Campl4チュートリアル)

を見ながら試したところ以下の感じでパースしていけそう・・・

#load "dynlink.cma";;
#load "camlp4o.cma";;
open Genlex

let lexer = make_lexer [ "#"; "("; ")";  ";" ]

let h_file = open_in "glext.h"

let h_stream = Stream.of_channel h_file

let tok_stream = lexer h_stream

let directive = parser
    [< 'Ident "ifdef"; 'Ident x >] -> "#ifdef" ^ " " ^ x
  | [< 'Ident "ifndef"; 'Ident x >] -> "#ifndef" ^ " " ^ x
・・・・・

う~ん。このままやっていくと結局yaccとかを使うのと同じくらいの手間がかかりそう。
もちろん、ソース内に構文定義も書けるから1ファイルですむので今回の書き捨てプログラムのような目的には適しているけど、まっとうにCのヘッダーを解析しようとすると結構本気で構文ツリーを組み立てないといけないと思うので、さすがにそれは脱線しすぎ。

Delphiで作った自前の関数で必要なところだけ解析するほうが圧倒的に早いから今回の目的でOCamlを使うのはやめておこう。

でも、強い静的型付けは非常に好みだし、まだしっくり手にはなじんでないけど、型推論とか多相バリアント、強力なパターンマッチング等は非常に面白い。複数引数の関数は1引数の関数を返す関数を多層化したもの(カリー化?)をという考え方も新鮮です。

前に書いたVHDLの構文解析の作り直し時にはぜひ使いたい。

|

« Ocaml | トップページ | iPad »

プログラミング」カテゴリの記事

コメント

You could definitely see your expertise within the work you write.
The arena hopes for even more passionate writers such as you who
are not afraid to say how they believe. Always go after your heart.

投稿: Can A Minor Serve Alcohol In Queensland Today? | 2022年4月10日 (日) 20時00分

We are a group of volunteers and opening a new scheme in our community.
Your site offered us with valuable information to work on. You've done a formidable job and our whole
community will be thankful to you.

投稿: Taylor Port Wine Sold Near Me? | 2022年4月11日 (月) 14時47分

I read this article completely on the topic of the difference of latest and
earlier technologies, it's awesome article.

投稿: Marsha | 2022年4月13日 (水) 14時22分

この記事へのコメントは終了しました。

トラックバック


この記事へのトラックバック一覧です: OCamlでパース:

« Ocaml | トップページ | iPad »