2017-01-04 37 views
0

我有一個簡單的DSL應該爲表達式生成異步代碼(這是我可以拿出來說明我的觀點的最簡單的例子)。我剛加入scripting example一個新async聲明:如何爲XExpression子類型生成代碼?

grammar org.xtext.scripting.Scripting with org.eclipse.xtext.xbase.Xbase 

generate scripting "http://www.xtext.org/scripting/Scripting" 
import "http://www.eclipse.org/xtext/xbase/Xbase" as xbase 

Script returns xbase::XBlockExpression: 
    {Script} 
    (expressions+=XExpressionOrVarDeclaration ';'?)*; 

XExpression returns xbase::XExpression: 
    super | Async 
; 

Async: 
    'async' expression=XExpression 
; 

的想法是,該async代碼在另一個線程中執行。

我的問題是,我如何使用ScriptingJvmModelInferrer生成代碼爲Async.expression

在最簡單的情況下,我只是從這樣的Async.expression包裝代碼?

AsyncRunner.exec(new Runnable() { 
     @Override 
     public void run() { 
      // the Async.expression would end up here 
     } 
    }) 

在哪裏掛鉤做到這一點?

+0

我想我已經發現在HTTPS的示例://eclipse.org/Xtext/documentation/207_template.html(模板語言)請參閱*擴展編譯器* –

回答

0

如果擴展的Xbase你後容易不apapt的JvmModelInferrer編譯但你延長XbaseTypeComputerXbaseCompiler.doInternalToJavaStatement/internalToConvertedExpression(根據您實際引進)

0

你必須要更換3:

  1. 擴展編譯器以處理您的語言。關鍵是要處理Async表達式。

    class ScriptingCompiler extends XbaseCompiler { 
    
        override protected doInternalToJavaStatement(XExpression expr, ITreeAppendable it, boolean isReferenced) { 
         switch expr { 
          Async : { 
           newLine 
           append(''' 
            AsyncRunner.exec(new Runnable() { 
             @Override 
             public void run() {''') 
           expr.expression.doInternalToJavaStatement(it, false) 
           newLine 
           append('}});') 
    
          } 
    
          default : 
           super.doInternalToJavaStatement(expr, it, isReferenced) 
         } 
        } 
    
        override protected internalToConvertedExpression(XExpression obj, ITreeAppendable it) { 
         if (hasName(obj)) 
          append(getName(obj)) 
         else 
          super.internalToConvertedExpression(obj, it) 
        } 
    } 
    
  2. 類型表達的必須指定

    class ScriptingTypeComputer extends XbaseWithAnnotationsTypeComputer { 
    
        override computeTypes(XExpression expression, ITypeComputationState state) { 
         if(expression instanceof Async) { 
          super.computeTypes(expression.expression, state); 
         } else { 
          super.computeTypes(expression, state) 
         } 
        } 
    } 
    
  3. 兩個擴展具有要被注入:

    class ScriptingRuntimeModule extends AbstractScriptingRuntimeModule { 
        def Class<? extends XbaseCompiler> bindXbaseCompiler() { 
         return ScriptingCompiler 
        } 
    
        def Class<? extends ITypeComputer> bindITypeComputer() { 
         return ScriptingTypeComputer 
        } 
    }