是否可以通过标准输入将源代码通过管道传输到 GHC?

Is it possible to pipe source code to GHC through standard input?

我的意思是这样的:

echo 'main = print 1' | ghc > executable

GHC 回复:ghc: no input files

我错过了什么吗?这有可能吗?

通常 ghc 用作编译器,您 运行 它在文件上(ghc 可以在文件上查找并从结尾等推断类型)并将输出文件指定为标志。

不过,您当然可以使用

filename=$(mktemp --suffix=.hs)
echo "main = print 1" >> $filename
ghc -o executable $filename 

据我所知,答案是否定的。我的尝试:

  1. $ echo 'main = print 1' | ghc ghc: no input files

  2. $ echo 'main = print 1' | ghc - ghc: unrecognised flag: -

  3. $ echo 'main = print 1' | ghc /dev/stdin target ‘/dev/stdin’ is not a module name or a source file

  4. $ ln -s /dev/stdin stdin.hs; echo 'main = print 1' | ghc stdin.hs stdin.hs: hFileSize: inappropriate type (not a regular file)

问题:ghc 使用 .hs.lhs.o 等后缀来决定如何处理文件(这就是 #3 失败的原因)。即使你绕过那个(#4),ghc 真的想要 stat() 文件来获得它的大小,这在管道上失败了。

尽管这对于允许 "file" 比传统进程替换更像一个真实文件(通过创建一个实际的临时文件)的普通 process substitution, zsh provides a special kind of process substitution-like behavior 是不可能的:

% ghc -o Main -x hs =( echo 'main = print 1' )
[1 of 1] Compiling Main             ( /tmp/zshjlS99o, /tmp/zshjlS99o.o )
Linking Main ...
% ./Main
1
% 

-x hs 选项告诉 ghc 就像给定的文件名以 .hs 结尾一样。

总的来说,这本质上是一种围绕手动创建和删除临时文件的快捷方式。

我不确定是否有其他 shell 支持这种东西。我认为 bash 至少不会。

这可能不是您想要的,但作为 melpomene 已经 ,runghc 可以做到这一点。我认为它应该有自己的答案:

runghc <<< 'main = print 123'

Try it online