Skip to content

Instantly share code, notes, and snippets.

@martijndwars
Last active December 12, 2017 10:34
Show Gist options
  • Save martijndwars/b0b2d5c4a80107ab92acc1adc6868525 to your computer and use it in GitHub Desktop.
Save martijndwars/b0b2d5c4a80107ab92acc1adc6868525 to your computer and use it in GitHub Desktop.
Parse a string in a .spoofax-language using Scala's REPL

Create an empty project with SBT:

sbt new sbt/scala-seed.g8

Update build.sbt to contain the Metaborg repository:

import Dependencies._

lazy val root = (project in file(".")).
  settings(
    inThisBuild(List(
      organization := "com.example",
      scalaVersion := "2.12.3",
      version      := "0.1.0-SNAPSHOT"
    )),
    name := "Hello",
    resolvers += Resolver.mavenLocal,
    resolvers += "Metaborg Release Repository" at "http://artifacts.metaborg.org/content/repositories/releases/",
    resolvers += "Metaborg Snapshot Repository" at "http://artifacts.metaborg.org/content/repositories/snapshots/",
    libraryDependencies += "org.metaborg" % "org.metaborg.core" % "2.4.0-SNAPSHOT",
    libraryDependencies += "org.metaborg" % "org.metaborg.util" % "2.4.0-SNAPSHOT",
    libraryDependencies += "org.metaborg" % "org.metaborg.spoofax.core" % "2.4.0-SNAPSHOT",
    libraryDependencies += scalaTest % Test
  )

Open the REPL:

sbt consoleQuick

Load language:

val s = new org.metaborg.spoofax.core.Spoofax()
val r = s.resourceService.resolve("/Users/martijn/Projects/java-front/lang.java/target/lang.java-1.0.0-SNAPSHOT.spoofax-language")
val l = s.languageDiscoveryService.languageFromArchive(r)

Parse a string:

val i = s.unitService.inputUnit("class $ID {}", l, null)
val u = s.syntaxService.parse(i);
println(u.ast)

Print a term:

import com.google.common.collect.Iterables
import org.metaborg.core.project.ISimpleProjectService
val project = s.projectService.asInstanceOf[ISimpleProjectService].create(r)
val context = s.contextService.getTemporary(r, project, l);
val component = Iterables.get(l.components(), 0);
val interpreter = s.strategoRuntimeService.runtime(component, context, false);
val factory = s.termFactoryService.getGeneric
val term = factory.makeAppl(factory.makeConstructor("Program", 1), factory.makeList())
val text = s.strategoCommon.invoke(interpreter, term, "pp-debug");
@martijndwars
Copy link
Author

martijndwars commented Dec 10, 2017

  • If you want to disable imploding, specify a parser configuration:
val p = new org.metaborg.spoofax.core.syntax.JSGLRParserConfiguration(false, false)
val i = s.unitService.inputUnit("\"\\\"//", l, null, p)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment