Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Newer
Older
100644 269 lines (235 sloc) 8.889 kb
6e516fb @zot making REPL work in browsers
authored
1 if window? and (!global? or global == window)
2 window.global = window
3 window.ReplCore = root = {}
c5d3417 @zot spelled Leisure properly
authored
4 Leisure = window.Leisure
7b9d7bc @zot simple pretty printing, list constructors (need work)
authored
5 P = window.Pretty
17facf4 @zot fixed monads in browser REPL
authored
6 Prim = window.Prim
6e516fb @zot making REPL work in browsers
authored
7 else root = exports ? this
8
c5d3417 @zot spelled Leisure properly
authored
9 if !Leisure? and require?
10 Leisure = require('./leisure')
7b9d7bc @zot simple pretty printing, list constructors (need work)
authored
11 P = require('./pretty')
20fce92 @zot tweaked monads, added bind function
authored
12 Prim = require('./prim')
72bd694 @zot Browser version seems to work, now
authored
13 U = require('util')
6e516fb @zot making REPL work in browsers
authored
14
15 compileFunc = ->
16
17 setCompiler = (c)-> compileFunc = c
18
19 nextFunc = ->
20
21 setNext = (n)-> nextFunc = n
22
c90d5ea @zot added :r command to REPL, removed global arg from define,
authored
23 resetFunc = null
24
25 setResetFunc = (func)-> resetFunc = func
26
c5d3417 @zot spelled Leisure properly
authored
27 getType = Leisure.getType
72bd694 @zot Browser version seems to work, now
authored
28
22c2206 @zot leisure stack in error msgs, now
authored
29 formatContexts = (stack)->
30 for [funcName, offset] in stack.toArray()
31 [src, start, end] = Leisure.funcContextSource funcName, offset
32 "#{funcName}:#{start},#{end}: #{Leisure.indent "#{src.substring(0, start)} << #{src.substring(start, end)} >> #{src.substring(end)}", 4}"
33
34 errString = (err)->
35 if err instanceof Error
36 "#{if err.leisureContext? then "\n#{err}:\n #{formatContexts(err.leisureContext).join('\n ')}\n\n" else ''}#{err.stack}"
37 else err
38
c8f4883 @zot output in doc
authored
39 handlerFunc = (ast, result, a, c, r, src, env)->
40 env = env ? Prim.defaultEnv
22c2206 @zot leisure stack in error msgs, now
authored
41 if ast?.err?
42 env.write errString ast.err
092dfd0 @zot errors if you redefine a function, now
authored
43 nextFunc()
d18ae11 @zot better error handling
authored
44 else
45 if a
1e5f48d @zot highlighting partially applied functions (when possible), track arity fo...
authored
46 # env.write("PARSED: #{Leisure.astPrint(ast)}\n")
c8f4883 @zot output in doc
authored
47 env.write("FORMATTED: #{P.print ast}\n")
c8d0629 @zot cleaned up notebook
authored
48 if c then env.write("GEN: #{ast.src}\n")
d18ae11 @zot better error handling
authored
49 if r
c8b1ac5 @zot added `xxx` to quote token functions, better error reporting, fixed REPL...
authored
50 if !result?
c8f4883 @zot output in doc
authored
51 env.write("(No Result)\n")
092dfd0 @zot errors if you redefine a function, now
authored
52 nextFunc()
d18ae11 @zot better error handling
authored
53 else
a031e97 @zot added $0 to hold the last result in the REPL, made compiler remove old *...
authored
54 global.$0 = result
c8f4883 @zot output in doc
authored
55 env.write("#{getType result}: #{P.print(result)}\n")
d18ae11 @zot better error handling
authored
56 processResult result
6e516fb @zot making REPL work in browsers
authored
57
58 setHandler = (f)-> handlerFunc = f
59
c8d0629 @zot cleaned up notebook
authored
60 helpFunc = (env)->
4cec9c6 @zot Checkpointing debug contexts -- still works with no -g
authored
61 (env ? Prim.defaultEnv).write("""
c5d3417 @zot spelled Leisure properly
authored
62 Type a Leisure expression or one of these commands and hit enter:
6e516fb @zot making REPL work in browsers
authored
63
64 :h -- display this help
c90d5ea @zot added :r command to REPL, removed global arg from define,
authored
65 :c filename -- compile file
c5d3417 @zot spelled Leisure properly
authored
66 :r -- reset the Leisure environment
6e516fb @zot making REPL work in browsers
authored
67 :v -- display variable values
68 :v var value -- set a variable
69 :q -- quit
c5d3417 @zot spelled Leisure properly
authored
70 ! code -- eval JavaScript code in the leisure environment
a31333f @zot sandbox work
authored
71 !! code -- eval JavaScript code in the host environment
6e516fb @zot making REPL work in browsers
authored
72
73 """)
74
75 setHelp = (h)-> helpFunc = h
76
77 vars = {
78 c: [false, 'show generated code'],
79 a: [false, 'show parsed AST'],
80 r: [true, 'show evaluation result'],
81 }
82
83 print = (args...)-> writeFunc(U.format.apply(null, args))
84
85 write = (args...)-> writeFunc args.join('')
86
88083f3 @zot better demo text in ast.html and demo.html, env-based presentation, forw...
authored
87 processResult = (result, env, next)->
88 next = next ? nextFunc
89 if (getType result) == 'monad' then Prim.runMonad result, (env ? Prim.defaultEnv), -> next()
90 else next()
963f35b @zot starting on monads
authored
91
c8d0629 @zot cleaned up notebook
authored
92 handleVar = (name, value, env)->
6e516fb @zot making REPL work in browsers
authored
93 if !name
94 for prop in (k for k of vars).sort()
c8d0629 @zot cleaned up notebook
authored
95 env.write("#{prop} = #{vars[prop][0]} -- #{vars[prop][1]}\n")
96 else if !value and !vars[name] then env.write("No variable named #{name}\n")
97 else if !value then env.write("#{name} = #{vars[name]} -- #{vars[prop][1]}\n")
e434f17 @zot removed prim from ASTs, added pretty printing for ASTs
authored
98 else vars[name][0] = !(value[0] in ['f', 'F'])
6e516fb @zot making REPL work in browsers
authored
99
c5d3417 @zot spelled Leisure properly
authored
100 # rewrite in Leisure
663c45b @zot added source to compiled defines (for AST inpsection), C-ENTER, M-ENTER,...
authored
101 processLine = (line, env, namespace)->
1bdca54 @zot ripped sandbox out from cmdline REPL, for now
authored
102 env = env ? Prim.defaultEnv
6e516fb @zot making REPL work in browsers
authored
103 try
104 if line
f3cfe1d @zot ! works in browsers, now (but doesn't inspect, yet), lone exprs in files...
authored
105 if line[0] == '!'
a31333f @zot sandbox work
authored
106 if line[1] == '!'
107 result = eval(line.substr(2))
108 result = if U? then U.inspect(result) else result
1bdca54 @zot ripped sandbox out from cmdline REPL, for now
authored
109 env.write("#{result}\n")
a31333f @zot sandbox work
authored
110 else
c5d3417 @zot spelled Leisure properly
authored
111 result = Leisure.eval(line.substr(1))
a31333f @zot sandbox work
authored
112 result = if U? then U.inspect(result) else result
1bdca54 @zot ripped sandbox out from cmdline REPL, for now
authored
113 env.write("#{result}\n")
c8d0629 @zot cleaned up notebook
authored
114 else if (m = line.match(/^:v\s*(([^\s]*)\s*([^\s]*)\s*)$/)) then handleVar(m[2], m[3], env)
115 else if (m = line.match(/^:c\s*([^\s]*)$/)) then return compileFunc(m[1], env)
c90d5ea @zot added :r command to REPL, removed global arg from define,
authored
116 else if (m = line.match(/^:r/)) then resetFunc()
c8d0629 @zot cleaned up notebook
authored
117 else if (line.trim() == ':h') then helpFunc(env)
118 else if (line.trim() == ':q') then process.exit(0)
119 else
120 [a, c, r] = [vars.a[0], vars.c[0], vars.r[0]]
4cec9c6 @zot Checkpointing debug contexts -- still works with no -g
authored
121 [ast, err] = Leisure.compileNext(line, getGlobals(), false, false, false, namespace, env.debug)
66c67d3 @zot removed obsolete code from leisure.cs
authored
122 if err?
123 if ast? then ast.err = err
124 else ast = {err: err}
4cec9c6 @zot Checkpointing debug contexts -- still works with no -g
authored
125 else [ast, result] = if r then Leisure.evalNext(line, namespace, env.debug) else [ast, null]
c8d0629 @zot cleaned up notebook
authored
126 return handlerFunc(ast, result, a, c, r, line, env)
6e516fb @zot making REPL work in browsers
authored
127 catch err
22c2206 @zot leisure stack in error msgs, now
authored
128 env.write errString err
6e516fb @zot making REPL work in browsers
authored
129 nextFunc()
130
eba0366 @zot fixed repl to import properly, again,
authored
131 escape = (str)-> str.replace(/\n/g, '\\n')
132
d2d47e6 @zot checkpoint with debug contexts
authored
133 prelude = """
134 setType = Leisure.setType;
135 setDataType = Leisure.setDataType;
136 define = Leisure.define;
137 defineMacro = Leisure.defineMacro;
138 defineToken = Leisure.defineToken;
139 processResult = Repl.processResult;
140 setContext = Leisure.setContext;
141 funcContext = Leisure.funcContext;
142 Nil = Leisure.Nil;
143 cons = Leisure.cons;
144 """
145
be963e9 @zot refactored context tracking code generation
authored
146 localPrelude = prelude.replace(/\n/g, "\nvar ")
d2d47e6 @zot checkpoint with debug contexts
authored
147
4cec9c6 @zot Checkpointing debug contexts -- still works with no -g
authored
148 generateCode = (file, contents, loud, handle, nomacros, check, debug)->
88083f3 @zot better demo text in ast.html and demo.html, env-based presentation, forw...
authored
149 [globals, errs, auto] = findDefs contents, nomacros, loud
150 if auto
151 console.log "auto: '#{auto}'"
4cec9c6 @zot Checkpointing debug contexts -- still works with no -g
authored
152 processResult Leisure.evalNext(auto, 'Leisure.', debug)[1], {}, ->
153 generate file, contents, loud, handle, nomacros, check, globals, errs, debug
154 else generate file, contents, loud, handle, nomacros, check, globals, errs, debug
88083f3 @zot better demo text in ast.html and demo.html, env-based presentation, forw...
authored
155
4cec9c6 @zot Checkpointing debug contexts -- still works with no -g
authored
156 generate = (file, contents, loud, handle, nomacros, check, globals, errs, debug)->
2110e65 @zot file loading in browser, handle compiled def references (Code.globals)
authored
157 if loud then console.log("Compiling #{file}:\n")
ffe42d4 @zot made 'require' monad (for both cmdline and browser, but not tested in cm...
authored
158 objName = if file? and file.match /\.lsr$/ then file.substring(0, file.length - 4) else file ? '_anonymous'
963f35b @zot starting on monads
authored
159 out = """
ffe42d4 @zot made 'require' monad (for both cmdline and browser, but not tested in cm...
authored
160 var #{objName} = (function(){
59a74da @zot trying to make sandbox cleaner -- browser still seems to retain defs aft...
authored
161 var root;
162
163 if ((typeof window !== 'undefined' && window !== null) && (!(typeof global !== 'undefined' && global !== null) || global === window)) {
989bc5d @zot changed *.laz to *.lsr
authored
164 #{if file? then file.replace(/\.lsr/, '') + ' = ' else ''}root = {};
59a74da @zot trying to make sandbox cleaner -- browser still seems to retain defs aft...
authored
165 global = window;
166 } else {
167 root = typeof exports !== 'undefined' && exports !== null ? exports : this;
c5d3417 @zot spelled Leisure properly
authored
168 Leisure = require('./leisure');
169 Leisure.req('./std');
963f35b @zot starting on monads
authored
170 require('./prim');
65508ce @zot seems to work in sandbox
authored
171 ReplCore = require('./replCore');
963f35b @zot starting on monads
authored
172 Repl = require('./repl');
173 }
59a74da @zot trying to make sandbox cleaner -- browser still seems to retain defs aft...
authored
174 root.defs = {};
175 root.tokenDefs = [];
5327c67 @zot macros seem to work, started work on do macro, improved pretty printing ...
authored
176 root.macros = {};
59a74da @zot trying to make sandbox cleaner -- browser still seems to retain defs aft...
authored
177
d2d47e6 @zot checkpoint with debug contexts
authored
178 #{localPrelude}
963f35b @zot starting on monads
authored
179 """
fb57e61 @zot added -v option to runRepl, made runRepl with no -c still give prompt on...
authored
180 names = globals
181 prev = Leisure.Nil
838ad3b @zot started on notebook. mark up functions in doc.
authored
182 if err then throw new Error(err)
65508ce @zot seems to work in sandbox
authored
183 defs = []
66c67d3 @zot removed obsolete code from leisure.cs
authored
184 rest = contents
48ce68e @zot fixed compile error for files with only naked exprs
authored
185 varOut = ''
82b61df @zot new parser works, bracketing works
authored
186 for v, i in globals.toArray()
48ce68e @zot fixed compile error for files with only naked exprs
authored
187 if i > 0 then varOut += ","
188 varOut += " #{Leisure.nameSub v}"
189 if varOut then out += "\nvar#{varOut};\n"
c5d3417 @zot spelled Leisure properly
authored
190 globals = Leisure.append(globals, getGlobals())
5f736b7 @zot fixed empty code issue in generateCode
authored
191 while rest and rest.trim()
fb57e61 @zot added -v option to runRepl, made runRepl with no -c still give prompt on...
authored
192 if loud > 1 and prev != names and names != Leisure.Nil then console.log "Compiling function: #{names.head}"
d8acdfe @zot new code gen works
authored
193 oldRest = rest
4cec9c6 @zot Checkpointing debug contexts -- still works with no -g
authored
194 [ast, err, rest] = Leisure.compileNext rest, globals, null, check, nomacros, 'Leisure.', debug
6e6a474 @zot still testing new parser
authored
195 if ast?.leisureName?
fb57e61 @zot added -v option to runRepl, made runRepl with no -c still give prompt on...
authored
196 prev = ast.leisureName
197 names = names.tail
171d5e3 @zot newlines in front of lambda bodies work
authored
198 code = if rest then oldRest.substring(0, oldRest.length - rest.length) else ''
5e98bff @zot allow python-style indentation
authored
199 err = err ? ast?.err
200 if err
6e6a474 @zot still testing new parser
authored
201 errs = "#{errs}#{if ast?.leisureName then "Error in #{ast.leisureName}#{showAst ast}" else ""}#{err}\n"
5e98bff @zot allow python-style indentation
authored
202 rest = ''
203 else if ast
d8acdfe @zot new code gen works
authored
204 globals = ast.globals
c5d3417 @zot spelled Leisure properly
authored
205 m = code.match(Leisure.linePat)
206 nm = ast.leisureName
59a74da @zot trying to make sandbox cleaner -- browser still seems to retain defs aft...
authored
207 ast.src = """
5327c67 @zot macros seem to work, started work on do macro, improved pretty printing ...
authored
208 //#{if nm? then nm + ' = ' else ''}#{escape(P.print(ast))}
c5d3417 @zot spelled Leisure properly
authored
209 #{if nm? then "root.defs.#{Leisure.nameSub(nm)} = #{Leisure.nameSub(nm)} = " else ""}#{ast.src}
59a74da @zot trying to make sandbox cleaner -- browser still seems to retain defs aft...
authored
210 """
c5d3417 @zot spelled Leisure properly
authored
211 src = if ast.leisureName
212 defs.push Leisure.nameSub(ast.leisureName)
65508ce @zot seems to work in sandbox
authored
213 ast.src
214 else "processResult(#{ast.src})"
d8acdfe @zot new code gen works
authored
215 out += "#{src};\n"
ac53a01 @zot load file in browser repl
authored
216 [a, c, r] = [vars.a[0], vars.c[0], vars.r[0]]
217 if handle then handlerFunc ast, null, a, c, r, code
65508ce @zot seems to work in sandbox
authored
218 out += """
59a74da @zot trying to make sandbox cleaner -- browser still seems to retain defs aft...
authored
219
56ed337 @zot fixed code generation
authored
220 if (typeof window !== 'undefined' && window !== null) {
c5d3417 @zot spelled Leisure properly
authored
221 Leisure.processTokenDefs(root.tokenDefs);
56ed337 @zot fixed code generation
authored
222 }
59a74da @zot trying to make sandbox cleaner -- browser still seems to retain defs aft...
authored
223 return root;
224 }).call(this)
65508ce @zot seems to work in sandbox
authored
225 """
d8acdfe @zot new code gen works
authored
226 if errs != '' then throw new Error("Errors compiling #{file}: #{errs}")
2110e65 @zot file loading in browser, handle compiled def references (Code.globals)
authored
227 out
228
c5d3417 @zot spelled Leisure properly
authored
229 getGlobals = -> Leisure.eval 'leisureGetFuncs()'
092dfd0 @zot errors if you redefine a function, now
authored
230
1e5f48d @zot highlighting partially applied functions (when possible), track arity fo...
authored
231 #showAst = (ast)-> if ast? then "(#{P.print(ast)})/(#{Leisure.astPrint(ast)})" else ""
232 showAst = (ast)-> if ast? then "(#{P.print(ast)})" else ""
6e6a474 @zot still testing new parser
authored
233
fb57e61 @zot added -v option to runRepl, made runRepl with no -c still give prompt on...
authored
234 findDefs = (contents, nomacros, loud)->
88083f3 @zot better demo text in ast.html and demo.html, env-based presentation, forw...
authored
235 auto = null
9145a66 @zot handle forward variable declarations
authored
236 errs = ''
c5d3417 @zot spelled Leisure properly
authored
237 globals = Leisure.Nil
9145a66 @zot handle forward variable declarations
authored
238 rest = contents
239 while rest
240 oldRest = rest
c5d3417 @zot spelled Leisure properly
authored
241 [ast, err, rest] = Leisure.compileNext rest, globals, true, null, nomacros
6e6a474 @zot still testing new parser
authored
242 if err
243 if ast?.leisureName then errs = "#{errs}Error in #{ast.leisureName}#{showAst ast}: #{err}\n"
244 else if prevName? then errs = "#{errs}Error after #{prevName}: #{err}\n"
4bdd58a @zot beginnings of AST printing
authored
245 else errs = "#{errs}#{err}\n"
88083f3 @zot better demo text in ast.html and demo.html, env-based presentation, forw...
authored
246 else
247 line = oldRest.substring(0, (if rest? then oldRest.length - rest.length else oldRest.length))
248 if line.match /(^|\n)#@auto/ then auto = line
c5d3417 @zot spelled Leisure properly
authored
249 if ast?.leisureName
6e6a474 @zot still testing new parser
authored
250 prevName = ast.leisureName
fb57e61 @zot added -v option to runRepl, made runRepl with no -c still give prompt on...
authored
251 if loud > 2 then console.log "Found function: #{ast.leisureName}"
6e6a474 @zot still testing new parser
authored
252 if globals?.find((v)->v == ast.leisureName) then throw new Error("Attempt to redefine function: #{ast.leisureName}#{showAst ast}")
c5d3417 @zot spelled Leisure properly
authored
253 globals = Leisure.cons(ast.leisureName, globals)
88083f3 @zot better demo text in ast.html and demo.html, env-based presentation, forw...
authored
254 [globals.reverse(), errs, auto]
4973dbf @zot adding support for forward refs
authored
255
6e516fb @zot making REPL work in browsers
authored
256 root.processLine = processLine
257 root.setCompiler = setCompiler
258 root.setHelp = setHelp
259 root.setNext = setNext
260 root.setHandler = setHandler
261 root.next = -> nextFunc()
262 root.help = -> helpFunc()
2110e65 @zot file loading in browser, handle compiled def references (Code.globals)
authored
263 root.getType = getType
264 root.generateCode = generateCode
3c0df11 @zot getting ready for separate environments
authored
265 root.processResult = processResult
c90d5ea @zot added :r command to REPL, removed global arg from define,
authored
266 root.setResetFunc = setResetFunc
838ad3b @zot started on notebook. mark up functions in doc.
authored
267 root.findDefs = findDefs
22c2206 @zot leisure stack in error msgs, now
authored
268 root.prelude = prelude
269 root.errString = errString
Something went wrong with that request. Please try again.