【问题标题】:XText programmatically parse a DSL script into an Ecore modelXText 以编程方式将 DSL 脚本解析为 Ecore 模型
【发布时间】:2012-08-05 18:25:36
【问题描述】:

我需要以编程方式将符合 XText 语法的文本转换为符合 XText 从相同语法生成的 Ecore 元模型的 AST。

我知道 XText 也会生成实现此类解析器的 Java 类,但我不知道它们在哪里以及如何使用它。

【问题讨论】:

    标签: eclipse eclipse-emf xtext


    【解决方案1】:

    这个问题的完整答案可以在 Eclipse wiki 的 Xtext page 上找到。

     new org.eclipse.emf.mwe.utils.StandaloneSetup().setPlatformUri("../");
     Injector injector = new MyDslStandaloneSetup().createInjectorAndDoEMFRegistration();
     XtextResourceSet resourceSet = injector.getInstance(XtextResourceSet.class);
     resourceSet.addLoadOption(XtextResource.OPTION_RESOLVE_ALL, Boolean.TRUE);
     Resource resource = resourceSet.createResource(URI.createURI("dummy:/example.mydsl"));
     InputStream in = new ByteArrayInputStream("type foo type bar".getBytes());
     resource.load(in, resourceSet.getLoadOptions());
     Model model = (Model) resource.getContents().get(0);
    

    将文件扩展名 (mydsl) 更改为您自己的语言扩展名。

    【讨论】:

      【解决方案2】:

      代码如下:

      @Inject
      ParseHelper<Domainmodel> parser
      
      def void parseDomainmodel() {
        // When in a vanilla Java application (i.e. not within Eclipse),
        // you need to run a global setup:
        val injector = new MyDslStandaloneSetup().createInjectorAndDoEMFRegistration
        injector.injectMembers(this) // sets the field 'parser'
      
        // this is how you can use it:
        val model = parser.parse(
          "entity MyEntity {
            parent: MyEntity
          }")
        val entity = model.elements.head as Entity
        assertSame(entity, entity.features.head.type)
      }
      

      另见http://www.eclipse.org/Xtext/documentation.html#TutorialUnitTests。

      【讨论】:

        猜你喜欢
        • 2013-03-05
        • 2012-03-12
        • 2018-09-16
        • 2010-11-16
        • 1970-01-01
        • 2016-04-16
        • 2022-01-06
        • 1970-01-01
        • 2013-06-17
        相关资源
        最近更新 更多