このフォーラムでそのような質問に対する回答を実際に検索しようとしましたが、これまでのところ何も機能していないようです。
次のようなメソッド宣言をタイプチェックしたい:
public int stackOverFlow() {int a; a = a + 1; return 0;}
戻り式の型は、メソッドの戻り型と一致する必要があります (この例では true です)。
私は、文法内のすべての非終端記号 (ノードの形式) とデフォルトの深さ優先ビジターの構文ツリーを生成する Java Tree Builder を使用しています。
Node インターフェイスを実装する MethodDeclaration クラスがあります。ノード インターフェイスには、次の形式の accept メソッドがあります。
public Node accept(TypeVisitor v){ return v.visit(v));
この受け入れメソッドにより、TypeVisitor が MethodDeclaration にアクセスできるようになります。
メソッド宣言にアクセスするには、単純な型チェックを 1 つ行います。
public Node visit(MethodDeclaration n){
// this visits the f10 Node, which is the return expression,
// and returns a specific Node object
Node rtype = n.f10.accept(this);
// this also does a similar thing by visitng the f1 Node,
// the method's return type, and returns a specific Node Object
Node acType = n.f1.accept(this);
// Now if I compare the two specific Node objects, it always fails.
if(rtype == acType){
//enter here
}
}
if-bodyに入らないのはなぜですか?私も試しrtype.equals(acType)
てみましたが、falseを返します。
rtype.toString.equals(acType.toString())
どちらもfalseを返すようにしました。
Eclipseデバッガーを使用してコードにステップインしようとしましたが、出力は次のとおりです。
rtype IntegerType (id=67)
acType IntegerType (id=69)
デバッガーの出力からわかるように、rtype と acType の両方が IntegerType オブジェクトです。
比較が失敗する理由は何ですか?
if(rtype instanceof IntegerType) を使用すると、これは true を返し、
if(acType instanceof IntegerType) を使用すると、これも true を返します。
しかし、オブジェクトの比較は常に失敗しますか?
私はJavaCC(パーサー生成用)、JTB(ASTおよびビジタークリエーター)、Eclipse、およびJava 1.7を使用しています