Zulip Chat Archive

Stream: lean4

Topic: MetaM String -> IO String


Quinn (Aug 15 2024 at 22:48):

hi! we're (@Alok Singh ) having trouble transforming MetaM to IO

import Lean

open Lean Elab Command Term Meta Parser

def parseString (s : String) : MetaM Syntax := do
  -- Parse the string into a `Syntax` object
  let env  getEnv
  let parserResult := Parser.runParserCategory env `module s
  -- only works on the happy path.
  return parserResult.toOption.get!

def readFile (path : String) : IO String := do
  let heading := s!"-- {path}\n"
  let contents  IO.FS.readFile path
  pure s!"{heading}{contents}"

def main : IO Unit := do
  let contents  readFile "Prooffusion/Fixture.lean"
  -- let (stx, s, ms) ← parseString contents |>.toIO
  IO.println contents

This is giving us

type mismatch
  fun ctxCore sCore => (parseString contents).toIO ctxCore sCore
has type
  Lean.Core.Context  Lean.Core.State  IO (Lean.Syntax × Lean.Core.State × Lean.Meta.State) : Type
but is expected to have type
  IO ?m.495 : Type

What's a cheap way to construct Core.Context and Core.State elements correctly?

Eric Wieser (Aug 15 2024 at 22:49):

What do you want env to contain? The environment in the loaded module?

Quinn (Aug 15 2024 at 23:55):

I think it should contain that, yeah. right now the IO is just for sanity check printing

Quinn (Aug 15 2024 at 23:55):

so it doesn't even have to contain anything, really, at first

Adam Topaz (Aug 16 2024 at 00:02):

There are various examples around that show how to do this

Adam Topaz (Aug 16 2024 at 00:02):

One way is to first convert to CoreM then use one of the variants of withImports

Adam Topaz (Aug 16 2024 at 00:06):

Here's an example to illustrate:

import Mathlib

open Lean

def foo (m : MetaM α) : IO α := CoreM.withImportModules #[`Mathlib] <| m.run'

#eval foo <| show MetaM Unit from do
  let env  getEnv
  println! env.constants.toList.length

Quinn (Aug 16 2024 at 20:13):

cool! this works as written when mathlib is imported, still figuring out how to make it work in a mathlib-free project

Quinn (Aug 16 2024 at 20:14):

unknown constant 'Lean.Core.CoreM.withImportModules'

Quinn (Aug 16 2024 at 20:17):

oh dropping CoreM with open Lean Meta solved namespace issue

Adam Topaz (Aug 16 2024 at 22:09):

CoreM.withImportModules is a relatively thin wrapper around a function from core IIRC. You could therefore probably roll your own version by looking at the code

Damiano Testa (Aug 17 2024 at 08:09):

For minimizing imports, try adding set_option linter.minImports true right after import Mathlib and see what it says.

With meta-code it may not perform too well, but it may still be useful.


Last updated: May 02 2025 at 03:31 UTC