Debian Codegraph @

Docs/Nasal-doc.tex

raw
1 % keep in mind: WriteLatex.com has by default a 30p(unregistered)/90p(logged in) limit (which only applies to the preview, not the PDF download! And it can be raised on demand): https://www.writelatex.com/help/3-is-writelatex-limited-to-30-pages-the-preview-stops-at-that-point
2
3 % actually, the preview works fine as an unregistered user - I think that's per document...
4
5 % scribtex.com provides a free mode, with 50MB of space, no page limit, git repository and full revision history: http://www.scribtex.com/ (being merged into www.sharelatex.com )
6
7 % contributors should ideally use this referral link, which gives us 50MB of additional space: https://www.writelatex.com/signup?ref=9a77e088e3aa (we're using only 1MB as of 03/2013)
8
9
10 % Section Ideas: Block Parser, Efficiency Guide and Erlang-style bitstring support
11 % and: creating a static call tree for Nasal code, to more easily create developer docs:
12 % bombable addon, advanced weather
13
14 \documentclass{article}
15
16 % \emph{Every} manual needs color:
17 \usepackage{color}
18 % So we can split across pages/lines:
19 \usepackage{longtable}
20 % For syntax highlighting
21 \usepackage{listings}
22 % From the homepage of www.writeLaTeX.com ;)
23 %\usepackage{todonotes}
24 % Or disable them:
25 \newcommand{\todo}[1]{}
26 \newcommand{\listoftodos}[0]{}
27
28 % For links using \url{www.google.com}, see http://en.wikibooks.org/wiki/LaTeX/Hyperlinks
29 \usepackage{hyperref}
30 % for xrefs and TOC linking
31 \usepackage{nameref}
32
33 % For fancier macros, see http://tex.stackexchange.com/questions/58628/optional-argument-for-newcommand
34 \usepackage{xifthen}
35
36 % http://ctan.org/pkg/cooltooltips
37 \usepackage{cooltooltips}
38
39 % Specify enumeration style: http://texblog.org/2008/10/16/lists-enumerate-itemize-description-and-how-to-change-them/
40 \usepackage{enumerate}
41
42 % for drawing memory layouts (i.e. naRef/naObj and GC_HEADER stuff)
43 % http://www.ctan.org/pkg/bytefield
44 % http://www.martin-demling.de/2011/06/memory-maps-in-latex-using-the-bytefield-package/
45 % http://queen.elektro.uni-miskolc.hu/~gati/references/latex/packages/bytefield.pdf
46 \usepackage{bytefield}
47
48 % for drawing graphs (i.e. parse trees), see: http://www.texample.net/tikz/
49 % docs: http://en.wikibooks.org/wiki/LaTeX/PGF/TikZ
50 % examples (for adaption) to be found at: https://github.com/MartinThoma/LaTeX-examples/tree/master/tikz
51 \usepackage{tikz}
52 \usepackage{tikz-qtree}
53 \usetikzlibrary{shapes,arrows,calc}
54 % TODO: we need a custom style for showing parse trees dumped from Nasal
55
56 % data structures like vectors and hashes are probably best visualized by using this: http://www.latex-community.org/forum/viewtopic.php?f=45&t=11769
57 % also see: http://tex.stackexchange.com/questions/93942/typesetting-classical-data-structures-in-tikz
58 % http://tex.stackexchange.com/questions/19286/how-should-i-draw-a-singly-double-linked-list
59 % % http://tex.stackexchange.com/questions/24305/some-problems-drawing-linked-lists-with-tikzs-matrix-library
60
61 % and for visualizing stack frames, use the drawstack package
62 % https://gitorious.org/tikz-goodies/tikz-goodies/blobs/0dffd069488fc812050e6ce5513736e83eaa666b/drawstack/stack-example.tex
63 \usepackage{drawstack}
64
65 % for even fancier illustrations, see
66 % http://tex.stackexchange.com/questions/52761/tikz-diagram-with-stacks-and-box
67
68 % listings styling, see: http://www.tjansson.dk/?p=419 and http://en.wikibooks.org/wiki/LaTeX/Source_Code_Listings
69 % it would be really nice if symbols (especially mathematical) could be made smaller; LaTeX as it stands does not typeset them well in lstlisting
70 \usepackage{textcomp}
71 \lstset{
72 tabsize=4,
73 rulecolor=,
74 basicstyle=\scriptsize,
75 upquote=false,
76 aboveskip={1.5\baselineskip},
77 columns=fullflexible,
78 showstringspaces=false,
79 extendedchars=true,
80 breaklines=true,
81 prebreak=\raisebox{0ex}[0ex][0ex]{\ensuremath{\hookleftarrow}},
82 frame=single,
83 showtabs=false,
84 showspaces=false,
85 showstringspaces=false,
86 identifierstyle=\ttfamily,
87 keywordstyle=\color[rgb]{0,0,1},
88 commentstyle=\color[rgb]{0.133,0.545,0.133},
89 stringstyle=\color[rgb]{0.627,0.126,0.941},
90 numbers=left,
91 stepnumber=3,
92 firstnumber=1,
93 numberfirstline=true,
94 literate=%
95 %{symbol}{replacement}size%
96 {->}{{$\rightarrow$}}2 %
97 }
98
99 % diff is not by default supported by lstlisting
100 % taken from: http://tex.stackexchange.com/questions/50176/highlighting-a-diff-file
101 \lstdefinelanguage{diff}{
102 morecomment=[f][\color{blue}]{@@}, % group identifier
103 morecomment=[f][\color{red}]-, % deleted lines
104 morecomment=[f][\color{green}]+, % added lines
105 morecomment=[f][\color{magenta}]{---}, % Diff header lines (must appear after +,-)
106 morecomment=[f][\color{magenta}]{+++},
107 }
108
109 % define a very basic style for nasal, with some custom keywords
110 % see: http://members.aon.at/mfranz/nasal.vim
111 % we should be able to use regex/sed to turn the vim file into usable LaTex markup
112 \lstdefinelanguage{nasal}{
113 keywords={func, var, if, elsif, else, for, foreach, forindex, while, me, arg, parents, nil, and, or, size, keys, append, pop, setsize, subvec, delete, num, streq},
114 comment=[l]\#,
115 string=[b]",
116 string=[b]',
117 }
118
119 % Add Nasal-code-specific keywords/types here
120 \lstdefinelanguage[NASL]{C}[ANSI]{C}{
121 morekeywords={naRef, naPtr, naObj, naStr, naVec, naHash, naCode, naFunc, naCCode, naGhost,
122 naGhostType, naContext, naCFunction}
123 }
124 \lstset{defaultdialect=[NASL]C}
125
126 % todo: we may also want to define a style for Nasal bytecode ?
127 % OP codes taken from: https://github.com/andyross/nasal/blob/master/src/code.h
128 \lstdefinelanguage{nasalbytecode}{
129 keywords={OP_NOT, OP_MUL, OP_PLUS, OP_MINUS, OP_DIV, OP_NEG, OP_CAT, OP_LT, OP_LTE, OP_GT, OP_GTE, OP_EQ, OP_NEQ, OP_EACH, OP_JMP, OP_JMPLOOP, OP_JIFNOTPOP, OP_JIFEND, OP_FCALL, OP_MCALL, OP_RETURN, OP_PUSHCONST, OP_PUSHONE, OP_PUSHZERO, OP_PUSHNIL, OP_POP, OP_DUP, OP_XCHG, OP_INSERT, OP_EXTRACT, OP_MEMBER, OP_SETMEMBER, OP_LOCAL, OP_SETLOCAL, OP_NEWVEC, OP_VAPPEND, OP_NEWHASH, OP_HAPPEND, OP_MARK, OP_UNMARK, OP_BREAK, OP_SETSYM, OP_DUP2,OP_INDEX, OP_BREAK2, OP_PUSHEND, OP_JIFTRUE, OP_JIFNOT, OP_FCALLH, OP_MCALLH, OP_XCHG2, OP_UNPACK, OP_SLICE, OP_SLICE2}
130 }
131
132
133 \newcommand{\comment}[1]{}%lol...
134
135 % Camel-case hypenation (doesn't work with macros around it, though)
136 % http://tex.stackexchange.com/questions/66593/automatic-camel-case-breaking:
137 \comment{
138 \makeatletter
139 \def\camelcase{\leavevmode\begingroup
140 \let\ifcase\iftrue
141 \def\or##1{%
142 \catcode`##1\active\uccode`\~`##1\uppercase{%
143 \def~{\egroup\penalty2\hbox\bgroup\string##1}}}%
144 \@Alph{}%
145 \@camelcase}
146
147 \def\@camelcase#1{\textbf{\hbox\bgroup#1\egroup}\endgroup}
148 \makeatother
149 }
150
151 % todo: href for types (naRef, naPtr, naObj etc) ?
152 \definecolor{type} {rgb}{0.8, 0.2, 0.0}
153 \definecolor{func} {rgb}{0.0, 0.3, 0.6}
154 \definecolor{fixme} {rgb}{0.5, 0.5, 0.5}
155 \definecolor{source} {rgb}{0.2, 0.4, 0.8}
156 \definecolor{opcode} {rgb}{0.0, 0.6, 0.2}
157 \definecolor{keyword}{rgb}{1.0, 0.0, 0.0} %nasal keywords used in the text (e.g. nil)
158
159 %todo: do we need a macro for Nasal library functions like cmp, sort, call etc ?
160
161 % Italic, e.g. for names of members, etc.
162 \newcommand{\name}[1]{{\it #1}}
163 % A type like int or naRef. Asterisks/ampersands belong outside of the argument but not plurality indicators (e.g. \type{naRefs}*)
164 \newcommand{\type}[1]{\textcolor{type}{\tt #1}}
165 % Any function, best to suffix with parentheses via the \fp\ macro (e.g. \func{naLex}\fp)
166 \newcommand{\func}[1]{\textcolor{func}{\tt #1}}
167 % A fixme, shows in grey (because it's embarrasing ;) )
168 \newcommand{\fixme}[1]{\textcolor{fixme}{#1}}
169 % Source -- what repository, for specifying paths
170 \newcommand{\src}[1]{\textcolor{source}{\it #1}}
171
172 %for important global macros
173 \newcommand{\globalmacro}[1]{\textcolor{func}{\tt #1}}
174 %for important local macros (local macros are UNDEF'ed after use)
175 \newcommand{\localmacro}[1]{\textcolor{func}{\tt #1}}
176 % a list of macros would be better implemented using the reference manual, i.e. automatically via doxygen - but I find the global/local info itself useful, i.e. certain macros are only available when in the parser/codegen/vm or gc - while others are truly "global" in that they are generally available after including nasal.h
177
178 % Link to a source file (e.g. lex.c). Syntax is:
179 % \nasalsourcefile{name.c}
180 % \\-name of file
181 % \nasalsourcefile[132]{name.c}
182 % \\-line number
183
184 % from http://tex.stackexchange.com/questions/58628/optional-argument-for-newcommand
185 \newcommand{\nasalsourcefile}[2][]{%
186 \ifthenelse{\isempty{#1}}%
187 {%
188 \textcolor{source}{%
189 \href{https://github.com/andyross/nasal/blob/master/src/#2}{#2}%
190 }%
191 }%
192 {%
193 \textcolor{source}{%
194 \href{https://github.com/andyross/nasal/blob/master/src/#2\#L#1}{#2}%
195 }%
196 }%
197 }
198
199 % Cite a file, using above. Parenthetical like:
200 % (file.c, line 152)
201 % or:
202 % (file.c)
203 \newcommand{\citesourcefile}[2][]{%
204 \ifthenelse{\isempty{#1}}%
205 {%
206 (\nasalsourcefile{#2})%
207 }%
208 {%
209 (\nasalsourcefile[#1]{#2}, line #1)%
210 }%
211 }
212
213
214 %for Nasal APIs
215 \newcommand{\nasalapi}[1]{\func{#1}}
216
217 %for Nasal keywords referenced in the text
218 \newcommand{\nasalkeyword}[1]{\textcolor{keyword}{#1}}
219
220 %for opcode listings; automatically hyperref's
221 % \BIG: for when this is the only content
222 % \Med: for when this is used in a sentence and shouldn't stick out
223 \newcommand{\OP} [1]{\hyperref[op:#1]{\textcolor{opcode}{OP\_#1}}}
224 \newcommand{\TOK}[1]{\textcolor{opcode}{TOK\_#1}}
225 \newcommand{\PREC}[1]{\textcolor{opcode}{PREC\_#1}}
226 \newcommand{\Op} [1]{\hyperref[op:#1]{\textcolor{opcode}{\sc Op\_#1}}}
227 \newcommand{\Tok}[1]{\textcolor{opcode}{\sc Tok\_#1}}
228 \newcommand{\Prec}[1]{\textcolor{opcode}{\sc Prec\_#1}}
229
230
231 % For parse trees:
232 \newcommand{\Token}[2][]{%
233 \ifthenelse{\isempty{#1}}%
234 {\TOK{#2}}%
235 {\TOK{#2} (value: #1)}%
236 }
237
238 % (Working) Test from http://tex.stackexchange.com/questions/1230/reference-name-of-description-list-item-in-latex
239 \makeatletter
240 \let\orgdescriptionlabel\descriptionlabel
241 \renewcommand*{\descriptionlabel}[1]{%
242 \let\orglabel\label
243 \let\label\@gobble
244 \phantomsection
245 \edef\@currentlabel{#1}%
246 %\edef\@currentlabelname{#1}%
247 \let\label\orglabel
248 \orgdescriptionlabel{#1}%
249 }
250 \makeatother
251
252
253 % Either an argument or a user-entered value (as per standard \TeX practice):
254 \newcommand{\param}[1]{$\langle$#1$\rangle$}
255 % To escape a char
256 \newcommand{\escape}[1]{$\backslash$#1}
257 % Allow a break
258 \newcommand{\br}{\penalty3}
259 % Function parens
260 \newcommand{\fp}{\textcolor{func}{()}}
261
262
263
264 \begin{document}
265 \title{Documentation for the Nasal Scripting Language}
266 \author{Philosopher \& Hooray}
267 \date{September 21st, 2013} %Started Jan 16, 2013
268 \maketitle
269 \tableofcontents
270 \listoftodos
271
272 \clearpage
273
274 %todo: provide some background on the tools used ?
275 %mention experiences based on hacking the interpreter?
276
277 \comment{
278 \begin{abstract}%%FIXME: an author's note sort of thingy?
279 I started this around January 16th, 2013, but it was not until at least a month later (February) that I understood the Nasal internals well enough to begin. One of the things that really spurred my understanding was taking a step back from the code and examining it in my mind -- or at least, the part which I had more recently read through. As I did this, questions about how it fit together in the whole scheme of things usually emerged (e.g. how does parseBlock work and relate to the \verb$tok->children$ member?) and when I faced those questions, I could usually form a hypothesis about how I might implement it and what would make sense to me. In almost every case, I would just scan over the code as say ``yup, that looks right'' and then I instantly understood it since {\it I} was the one who had invented it: I was no longer reading someone else's code, but rather my own.
280
281 %\subsection{Notes}
282 I use \src{DATA}, \src{FG}, \src{SG}, and \src{Andy} to refer to the separate repositories; fgdata, flightgear source, simgear source, and Andy's GitHub repository, respectively. Since every \type{naRef} can reference different objects, I refer to a \type{naRef} that should be of type T\_HASH as \type{naRef:naHash} and one that can be T\_CODE or T\_CCODE as \type{naRef:naCode/naCCode}.
283 \end{abstract}
284
285 \clearpage
286 }
287
288 % Disabled for "production"
289 \comment{
290 \section*{Structure \& Organization}
291 \addcontentsline{toc}{section}{Structure \& Organization}
292 \begin{enumerate}
293 \item WRT structure/organization, see \url{http://www.lua.org/manual/5.1/} (some of this would overlap with a doxygen-based RM that could be created automatically after adding more doxygen markup)
294 \item we should probably have a section on the main Nasal APIs (see nasal.h)?
295 \item Terminology: Introduce important concepts at the beginning of each section (what is a stack, what is a parser, what is a lexer, stack machine etc) or at least link to or quote wikipedia ?
296 \item introduce important macros in each section (Parser, Codegen, VM, GC)?
297 \item just highlighting important types/structs isn't as helpful as directly providing a downstripped source snippet, especially for people who are not reading this online, and who may not have access to a browser to browse the git repositories, I would prefer adding important structs to the manual, and referencing them using hrefs here (testing this currently on my ebook reader, and it rocks reading about Nasal there!)
298 \item thinking about it, it might be better to stop using line numbers and instead use functions/loops or conditional blocks as identifiers, after all, line numbers are likely to change over time, and it would be really awkward to update things here? And functions/loops are likely to be identical among different repos! At least, also mention non-line number identifiers for that case?
299 \item use drawstack package for drawing our stacks
300 \item add more code examples (copy/paste) so that people don't necessarily need to look at the repository at the same time?
301 \item we still need to come up with a tikz style for using automatically created parse trees here
302 \item we may want to add an introductory section on getting/building Nasal from source, so that people can get started experimenting directly
303 \end{enumerate}
304
305 \clearpage
306 }
307
308 \section*{Prerequisites}
309 \addcontentsline{toc}{section}{Prerequisites}
310 \hypertarget{section:Prerequisites}{}% see http://tug.org/pipermail/texhax/2007-November/009466.html
311 This manual assumes familiarity with the C programming language and requires programming experience, including advanced concepts such as pointers and bit manipulation, data structures, memory management and (possibly) the ability to build programs from source. If you need to brush up on your C knowledge, we recommend checking out some of the following resources first, some of which may only take a couple of minutes to review/work through to get up to speed:
312
313 \begin{enumerate}
314 \item \url{http://www.slideshare.net/petdance/just-enough-c-for-open-source-programmers}
315 \item \url{http://www.slideshare.net/amraldo/introduction-to-c-programming-7898353}
316 \item \url{http://www.slideshare.net/olvemaudal/deep-c}
317 \item \url{http://mindview.net/CDs/ThinkingInC/beta3}
318 \item \url{http://www.physics.drexel.edu/courses/Comp_Phys/General/C_basics/}
319 \item \url{http://www.learnconline.com/2010/03/introduction.html}
320 \item \url{http://publications.gbdirect.co.uk/c_book/}
321 \item \url{http://c-faq.com/index.html}
322 \end{enumerate}
323
324 % There are tons of good C/C++ courses available on YouTube
325
326 For web-based programming experiments, you may want to check out some online compilers, such as:
327
328 \begin{enumerate}
329 \item \url{http://www.learn-c.org/}
330 \item \url{http://codepad.org/}
331 \item \url{http://ideone.com}
332 \end{enumerate}
333
334 At least basic knowledge of Nasal (or a similar language like JavaScript) will be helpful, i.e. understanding the basic syntax (for the parsing section) will go a long way, for example:
335 % this is just to test our custom nasal style
336 \begin{lstlisting}[language=nasal]
337 # declare a function with a named argument
338 var hello = func(name) {
339 print("Hello ", name);
340 }
341 hello("world"); # call the function with one argument
342 \end{lstlisting}
343
344
345 If you are connected to the internet, you can learn more about the Nasal language itself by visiting these links:
346 \begin{enumerate}
347 \item \url{http://plausible.org/nasal/sample.nas} (example of syntax and usage)
348 \item \url{http://plausible.org/nasal/lib.html} (documentation of library functions)
349 \item \url{http://wiki.flightgear.org/Nasal} -- see some more specific articles like these to get started:
350 \begin{enumerate}[i.]
351 \item \url{http://wiki.flightgear.org/Nasal_Conditionals}
352 \item \url{http://wiki.flightgear.org/Nasal_Variables}
353 \item \url{http://wiki.flightgear.org/Nasal_Loops}
354 \item \url{http://wiki.flightgear.org/Nasal_Operators}
355 \end{enumerate}
356 \end{enumerate}
357
358
359 \section{Introduction to Nasal}
360 \todo{see Andy's original design document: \url{http://plausible.org/nasal/doc.html} }
361
362 Nasal is an Open-Source, Mult-Platform, Small, and Easily Embeddable Scripting Language designed by Andy Ross and released under the GNU LGPL license. It originally started out as ``NASL'' (acronym for Not Another Scripting Language) but was renamed due to a naming conflict with another, unrelated scripting language. Nasal was specifically designed to be used as an extension language in other programs and to be embedded by developers into their own programs, without any platform bloat. It supports various programming paradigms, such as functional programming, procedural, and object oriented programming (OOP), and runs on both 32bit and 64 bit platforms. It is written in ANSI C99 and its source code is small, compact, and completely self-contained, with a handwritten lexer and parser and no external dependencies, other than the standard C library (though it has several library bindings that can be optionally compiled). It's main usage has been in FlightGear (where it got first added in 2003), an open-source flight simulator, and in AlgoScore, an algorithmic music composition software, where Nasal is used to write the algorithms. Nasal can also be run standalone, through a command-line ``interactive'' REPL (read-eval-print-loop) interpreter using the GNU readline library.
363
364 Nasal is available from several different sources. Ross has a repository on GitHub (\url{https://github.com/andyross/nasal}), but he has said that he considers the SimGear sources to be the standard version (\url{http://gitorious.org/fg/simgear/trees/next/simgear/nasal} -- SimGear is a component in FlightGear, it currently does not include a standalone interpreter). AlgoScore also has Nasal in it's source tree (\url{http://svn.gna.org/viewcvs/algoscore/trunk/src/nasal/}), but it has not been updated in a while and SimGear's is more actively maintained. Most source code references made here are referring to Ross's GitHub repository for now.\todo{We should start moving to simgear/gitorious references...}
365
366 \comment{the patched interpreter we're using uses yet another repo, the "nasal-standalone" repository on gitorious, which is merged from Andy's and SimGear's Nasal interpreter and uses CMake instead of Autotools}
367
368 Nasal combines the advantages of a dynamically-typed scripting language with a clean syntax close to C and Javascript -- Nasal being inspired by ECMAScript -- and it has many modern features like multiple assignment expressions and named function arguments, as well as unique ones like access to namespaces in the native ``hash'' datatype. It supports object-oriented programming through hashes that can contain a mutable ``parents'' vector used in implementing multiple-inheritance. It has automatic memory management through a garbage collector (GC) and is designed to be minimally threadsafe, without requiring a global interpreter lock (GIL). Nasal as a language is very flexible, and both its integration into FlightGear and the variety of libraries that have been created in Nasal attest to this (e.g. see \src{FG}/src/Scripting/FGNasalSys.cxx and the \src{Andy}/lib/ and \src{Andy}/contrib/Ampere/ directories for an illustration of this flexibility).
369
370 For more on Nasal syntax and features, see \url{http://plausible.org/nasal} and \url{http://wiki.flightgear.org/Nasal_scripting_language}. Reading Andy's design document is also recommended, as many of the things that are alluded to will be explained here: \url{http://plausible.org/nasal/doc.html}.
371
372 \comment{
373 \todo{we should get in touch with Andy to get the github repository updated, and to get the cmake changes upstream}
374 \section{Getting, building and installing Nasal}
375 \subsection{Windows}
376 \subsection{Mac}
377 \subsection{Unix/Linux}
378 }
379
380 \section{Maintaining this Manual}
381 \todo{mention useful tools such as cscope, doxygen, Source Navigator NG}
382 This manual is very far from being complete, or up-to-date. If you want to help out by contributing, please contact Philosopher or Hooray (the authors) on the forum. It is written in LaTeX but shouldn't be difficult to pick up on sight. Both grammar/wording edits and contributions/revisions of topics will be welcome!
383
384 This manual is hosted on both writeLaTeX.com and in FGData.
385
386 \section{Document layout}
387 \comment{
388 Creating API:
389 Globals and Contexts
390 Variables
391 How to Create an API
392 Using CPPBind
393 Internals:
394 Parsing
395 Lexing
396 Block Parsing
397 Precedence Parsing
398 Generating Bytecode
399 Virtual Machine
400 Garbage Collection
401 Error and Exception Handling
402 Examples and Existing Work:
403 Nasal Maintenance
404 Introspection
405 Example APIs
406 Perl-Compatable-Regular-Expressions (PCRE)
407 SQLite
408 Cairo/GNU ToolKit (GTK)
409 FlightGear Canvas
410 FlightGear Positioned
411 }
412 This document is focused on the C/C++ sides of working with Nasal. There are many great tutorials out there for Nasal programming itself, please see the links under ``\hyperlink{section:Prerequisites}{Prerequisites}''.
413
414 First described are some of the building blocks of the source code -- basic things that are used throughout and need to be understood. Next the types of variables and their usage are detailed -- manuipulating variables is essential to creating a usable API. From those building blocks, methods for creating an API are described for those needing to integrate Nasal into a existing program. CPPBind -- an extension found in SimGear -- is the focus of the next chapter: it allows easy manipulation of Nasal types from C++, including automatic conversions using templates.
415
416 For those who are interested, there are many parts describing different core pieces of nasal. Steps of parsing: lexing, block \& precedence parsing, and code generation. Code running in the virtual machine -- this provides insight into many of the actual workings of the Nasal code that programmers write. There's also an article on Nasal's garbage collection and some of the problems FlightGear has faced regarding that. Efforts to improve the GC are welcome! Error and exception handling is the last topic, including how to recognize and handle errors while programming in C.
417
418 Cool examples of work done on improving Nasal or that exemplifies the concepts described above are found at the end of the document. This includes ongoing work on ``introspection'' (enhancing the ability of Nasal to debug itself and complementing the existing metaprogramming capabilities), potential ``Nasal maintenance'' tasks, and descriptions of the existing bindings for PCRE, SQLite, Cairo/GTK, FlightGear's Canvas and more.
419
420 \part{Creating an API: useful knowledge}
421
422 \section{Globals and Contexts}
423 \todo{document the globals struct and naContext, needs rewording (taken from PMs) also document initGlobals, init Context etc}
424
425 A Nasal context is basically the ``housekeeper'' struct that manages data for a single instance of an interpreter. \emph{All} interpreter-specific stuff is managed via the context, which is why you have pointers and data such as:
426
427 \begin{enumerate}
428 \item the execution-frame stack, its current top
429 \item the operand stack
430 \item various GC related data structures (marking, free pool memory elements)
431 \item error handling (via setjmp/longjmp/jmp\_buf)
432 \item support for sub contexts, i.e. Nasal scripts calling other scripts, calling other scripts via naCall() etc
433 \end{enumerate}
434
435 Look at some of the callbacks - the only way to know what data to operate on is by having a handle to the context, which in turn contains handles to the relevant program (opcodes), operand stack, frames, GC stuff and so on. Each variable that gets created via naNew*() needs to be tied to a context for GC'ing.
436
437 All extension functions operate via naContexts -- so the context is basically the ``instance'' of the interpreter. Also, if we have multiple contexts around, for example using threading, naContexts are a way to keep things separate, even though we may have multiple threads running their own Nasal interpreter instance.
438
439 \subsection{Using Nasal Sub Contexts}
440 \todo {document sub context API and usage, see cscope 'naSubContext(), and add code snippets'}
441
442 Subcontexts are needed whenever an extension function is called which in turn invokes another Nasal function as a callback. The most common use in Nasal is using the \nasalapi{call}\fp\ library function in \nasalsourcefile{code.c} to explicitly call a function, while specifying the complete environment. Using the \nasalapi{call}\fp\ function is also the only way to do exception handling in Nasal.
443
444 Additional examples on subcontext API usage can be found in the sort() implementation (sort\_cmp in \nasalsourcefile{lib.c}), where the extension function executes a callback that is passed via a naRef argument. Another example is to be found in the readline bindings (\nasalsourcefile{readline.c}), where the completion function can be provided as a Nasal callback. Also, the SQLite bindings (see \nasalsourcefile{sqlitelib.c}) provide another example on using Nasal sub contexts, where the \func{run\_query}\fp\ extension function provides support for running a Nasal-space callback.
445
446 Sub contexts are usually used to issue a \nasalapi{naCall}\fp\ from inside a Nasal extension function. After use, sub contexts should be freed using \nasalapi{na\-Free\-Context}\fp.
447
448 \section{Variables}
449 \todo{we can also look at automating bytefield'ing by dumping Nasal internals directly to Latex}
450 The main object type in Nasal is \type{naRef} and it either holds a reference to a Nasal object or it stores a number. A \type{naRef} is a union between a double-precision floating-point number and a pointer to another data type. Designating it as a pointer is done by setting a bitmask in the top bits of the double, which includes the whole exponent, sign, and a couple more bits in the mantissa. Setting the bits in this way makes the double a NaN (Not a Number, an invalid number) that will usually cause a floating-point error if used, since it is a singalling NaN (SNaN) versus a quiet NaN (QNaN). Depending on the system configuration (processor and OS), setting the bits has to be accomplished in different ways. For supported 64-bit systems/OS combinations, where all of the data in the pointer lies in the bottom 48 bits, the bits above that are set with a bitmask simple. For 32-bit systems, the layout in endianness-dependent (since it has to be in the ``top'' bits) and a magic number (see the \localmacro{REFMAGIC} macro) is stored in the top bits, again making it a NaN:
451
452 \begin{lstlisting}[language=C]
453 /* On supported 64 bit platforms (those where all memory returned from
454 * naAlloc() is guaranteed to lie between 0 and 2^48-1) we union the
455 * double with the pointer, and use fancy tricks (see data.h) to make
456 * sure all pointers are stored as NaNs. 32 bit layouts (and 64 bit
457 * platforms where we haven't tested the trick above) need
458 * endianness-dependent ordering to make sure that the reftag lies in
459 * the top bits of the double */
460
461 #if defined(NASAL_LE)
462 typedef struct { naPtr ptr; int reftag; } naRefPart;
463 #elif defined(NASAL_BE)
464 typedef struct { int reftag; naPtr ptr; } naRefPart;
465 #endif
466
467 #if defined(NASAL_NAN64)
468 typedef union { double num; void* ptr; } naRef;
469 #else
470 typedef union { double num; naRefPart ref; } naRef;
471 #endif
472 \end{lstlisting}
473
474 If that is a bit confusing to understand, consider the following picture (for 64-bit systems):\\\\
475 \begin{bytefield}[bitwidth=.5em]{64}
476 \bitheader{0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58,60,62} \\
477 \begin{rightwordgroup}{64-bit \\ Pointer}
478 \bitbox{48}{Pointer's bottom 48 bits (data)} & \bitbox{16}{bitmask} \\
479 \bitbox{64}{Full pointer -- all bits $\ge$ 48 must not be set}
480 \end{rightwordgroup} \\
481 \begin{rightwordgroup}{Double \\ Numeric}
482 \bitbox{52}{Fraction} & \bitbox{11}{Exponent} & \bitbox{1}{$\pm$} \\
483 \bitbox{64}{IEEE 754 double-precision floating point number}
484 \end{rightwordgroup} \\
485 \end{bytefield}
486
487 With this layout, we have a pointer that has 48 bits of data in its lower half overlaid on top of a double whose exponent, sign, and some of the mantissa are in the top 16 bits. Once these bits are set with a bitmask, the double becomes a NaN. For more on this, see \nasalsourcefile{data.h} and \nasalsourcefile{naref.h}.
488
489 The pointers to the other types are stored in a \type{naPtr} union that contains all the Nasal types, some of which, like \type{naStr} and \type{naHash}, can be used from Nasal; others, like \type{naObj} and \type{naCode}, cannot be directly accessed from Nasal, but are instead used by the underlying C code.
490 \begin{lstlisting}[language=C]
491 typedef union {
492 struct naObj* obj;
493 struct naStr* str;
494 struct naVec* vec;
495 struct naHash* hash;
496 struct naCode* code;
497 struct naFunc* func;
498 struct naCCode* ccode;
499 struct naGhost* ghost;
500 } naPtr;
501 \end{lstlisting}
502
503 These \type{naRefs} are the fundamental 'variable' structure of Nasal, and the closer one gets to the actual running of Nasal code, the more \type{naRefs} are used (e.g. from \nasalsourcefile{codegen.c} to \nasalsourcefile{code.c}, which is going from barely any \type{naRefs} to essentially as rich with \type{naRefs} as it gets).
504
505 An interesting thing to note is that some of the attributes of private, internal objects, like a function, are implemented using \type{naRefs} instead of their ``raw'' counterparts, like \type{naFunc}*. This is probably because all the methods that work with the types, e.g. \func{naHash\_get}, are implemented with \type{naRefs} (and those use \func{PTR(foo).hash}, etc., to fetch the raw data type), and so it is often much more convenient to use those methods since there are no ``raw'' equivalents to use. It also could be for consistency, i.e. a \type{naRef} is always going to be a fixed size independent of application (it is, after all, just a pointer/double combination). Sometimes this leads to assumptions about the type of a member/variable. This document uses the convention of \type{naRef:$\langle$type$\rangle$} to denote assumptions about type, like \type{naRef:naHash} for hashes, \type{naRef:naCode/naCCode} for executable code, and \type{naRef:double} for numbers. Violating these assumptions may cause code to crash!
506
507 \comment{The point of having naHash, naVec, naCode, naFunc and naGhost wrappers for the various lower level structures such as VecRec (for naVec) or HashRec (for naHash) is adding meta information, such as GC related fields, to each Nasal type, including the common \localmacro{GC\_HEADER} macro that is used by all Nasal types as the very first field.}
508
509 \subsection{Scalars}
510 Nasal tries to keep a notion of ``scalars'' as numbers or strings, like Perl -- in fact, this is what the builtin \func{typeof}\fp\ function will return instead of ``number'' or ``string''. While numbers and strings are still separate types behind the scenes, Nasal will try to automatically convert from one to the other when running code, e.g. making a number into a string when concatenating it, or vice-versa for mathematical operators. Most of the Nasal extension function libraries will convert between them as well, but be warned that some do not! Those that do not use simple checks like \globalmacro{IS\_STR}\fp\ and \globalmacro{IS\_NUM}\fp\ instead of converting first using \func{naStringValue}\fp\ and \func{naNumValue}\fp; this means that only if a value literally represents a string or number will it be used as such. Simple ways to convert on the Nasal side are using concatenation with an empty string and addition with 0 or using \func{num}\fp.
511
512 \subsection{Types}
513 Here's a reference to all of the raw types used in Nasal:
514
515 \subsubsection{Strings/T\_STR/\type{naStr}}
516 The \type{naStr} struct stores a string's length and either its data (if it is less than 16 characters) or a pointer to its data. Unlike C, which uses null-termination to determine the length of a string, Nasal explicitly stores the length of a string so that it can contain any characters whatsoever -- though it is null-terminated as well, since C code often needs to deal with it like it actually was a C \type{char}* array. Note that when using \nasalapi{naStr\_fromdata}, only a copy of the data is stored, so that Nasal code can mutate the string without affecting the original bytes.
517
518 By default strings are mutable, including results of concatenation or \func{substr}\fp. When used as a key in a hash, a particular string has its ``hashcode'' member set to non-zero, making it immutable. Using this method, constant strings in the code (literals enclosed in double- or single-quotes) are made immutable.
519
520 API functions:
521 \begin{lstlisting}[language=C]
522 // String utilities:
523 int naStr_len(naRef s); // get the length of a string
524 char* naStr_data(naRef s); // pointer to null-terminated data
525 naRef naStr_fromdata(naRef dst, const char* data, int len); // set a string's data and length
526 naRef naStr_concat(naRef dest, naRef s1, naRef s2); // concatenate two strings
527 naRef naStr_substr(naRef dest, naRef str, int start, int len); // take a subscript of a string
528 \end{lstlisting}
529
530
531 \subsubsection{Vectors/T\_VEC/\type{naVec}}
532 Vectors are resizeable arrays with automatic reallocation, using a standard multiply-by-two rule for expanding. In comparison with bigger languages like Python, Nasal's vector operations are rather basic, but they do provide enough functionality for most uses. Most extensions can be scripted using Nasal ``classes'' or optimized as C code.
533
534 API functions:
535 \begin{lstlisting}[language=C]
536 // Vector utilities
537 int naVec_size(naRef v); // get the size of a vector
538 naRef naVec_get(naRef v, int i); // get a specific element by index
539 void naVec_set(naRef vec, int i, naRef o); // set a specific element by index
540 int naVec_append(naRef vec, naRef o); // append to a vector
541 naRef naVec_removelast(naRef vec); // remove the last element
542 naRef naVec_removefirst(naRef vec); // remove the first element - only in SimGear!
543 void naVec_setsize(naRef vec, int sz); // set the size of a vector, padding with naNil()
544 \end{lstlisting}
545
546 \subsubsection{Hashes/T\_HASH/\type{naHash}}
547 Hashes are the unordered, associative container type in Nasal (no fancy name like ``dictionary''). Each string used as a hash key is made immutable via having its ``hashcode'' set -- this is simply storage for a special number used in looking up and setting strings.
548 \todo{Only added as a quick reference, patch interpreter to create bytefield dumps for hashes?}
549
550 API functions:
551 \begin{lstlisting}[language=C]
552 // Hash utilities:
553 int naHash_size(naRef h); // get the size of a hash - number of elements
554 int naHash_get(naRef hash, naRef key, naRef* out); // get a key - returns 1 if it is found
555 naRef naHash_cget(naRef hash, char* key); // get a key using char* - DEPRECATED!
556 void naHash_set(naRef hash, naRef key, naRef val); // set a key to a value
557 void naHash_cset(naRef hash, char* key, naRef val); // set a key using char* - DEPRECATED!
558 void naHash_delete(naRef hash, naRef key); // delete a key from a hash
559 void naHash_keys(naRef dst, naRef hash); // get a vector of all keys in the hash
560 \end{lstlisting}
561
562 \subsubsection{Functions/T\_FUNC/\type{naFunc}}
563 A Nasal function is essentially a wrapper for executable objects, which can be \type{naCodes} (written in Nasal) and \type{naCCodes} (written in C, i.e. extension functions). This allows one common type for executing both of these. It is also the only one of these three types which should appear in Nasal space: the other two are more `raw' and need to be wrapped and/or bound to a context before they are exposed. Each \type{naFunc} stores three \type{naRefs}: \name{code}, \name{namespace}, and \name{next}. \name{code} is the \type{naRef:naCode/naCCode} that should get executed, \name{namespace} is the parent namespace of the function (i.e. the first level of recursion after the locals), and \name{next} is the \type{naRef:naFunc:naCode} that is the next link in the chain of namespaces. Note that the last two members are only applicable to \type{naCodes} since \type{naCCodes} do not have their own Nasal-space symbols.
564
565 There is no API for functions.
566
567 \subsubsection{Nasal Fuctional Code/T\_CODE/\type{naCode}}
568 This carries the data behind either a Nasal \nasalkeyword{func}\{\} expression or a complete parsed file/script. In either case, these objects are generated during parsing, in particular the ``code generation'' stage, and returned by \func{naParseCode}. They consist of a \name{constants} block -- basically a static heap of allocated storage. This contains \type{naRef} constants, both scalars and \nasalkeyword{func}\{\} constructs, the bytecode of the function, and info on line numbers versus opcode indices. These are accessed separately using macros in \nasalsourcefile{data.h}, in particular since the constants are \type{naRefs} while the others are \type{unsigned shorts}.
569
570 There is no API for code objects.
571
572 \subsubsection{Ghosts/T\_GHOST/\type{naGhost}}
573 \todo{document examples to be found in iolib.c}
574 Garbage Collected Handle to Outside Things, i.e. raw C pointers wrapped in a \type{naGhost} struct and managed via the GC, using explicitly registered allocation/release functions for each ghost type.
575
576 API functions:
577 \begin{lstlisting}[language=C]
578 // Ghost utilities:
579 typedef struct naGhostType {
580 void(*destroy)(void*);
581 const char* name;
582 } naGhostType;
583 naRef naNewGhost(naContext c, naGhostType* t, void* ghost);
584 naGhostType* naGhost_type(naRef ghost);
585 void* naGhost_ptr(naRef ghost);
586 int naIsGhost(naRef r);
587 \end{lstlisting}
588
589 \subsubsection{Extension functions/\type{naCFunction}/\type{naCCode}}
590 \todo{document existing functions or rather the way they are implemented, standard library ?}
591 % also see: http://wiki.flightgear.org/Howto:Extend_Nasal
592 Nasal Extension functions are usually functions with static linkage written in C and callable from Nasal. They can, of course, work with C variables, like from a pointer stored in a Nasal ghost variable, from a C library, or anything else. They can also perform operations on Nasal variables through the Nasal API (see \nasalsourcefile{nasal.h} and the next section) -- essentially anything that can be done from Nasal, and in a potentially more efficient manner because it is compiled down to native machine code. Each of these extension functions must match this signature:
593
594 \begin{lstlisting}[language=C]
595 // The function signature for an extension function:
596 typedef naRef (*naCFunction)(naContext ctx, naRef me, int argc, naRef* args);
597 \end{lstlisting}
598
599 This uses a scheme like the \func{main}\fp\ function where there is \name{argc} -- the number of arguments -- and \name{args} -- a pointer to the actual arguments, which are \type{naRefs} in this case. The \name{me} reference is like ``self'' in general Python usage or ``this'' in C++, and is set to the value of left-hand side of an expression if it is a method call (e.g. the value of foo in \verb$foo.bar()$) or is \nasalkeyword{nil} otherwise (e.g. even in \verb$foo[`bar']()$, or just \verb$fn()$). (Note that this would primarily be used for methods operating on ghost objects.) The context is of course the currently executing context, which is used to bind new \type{naRefs} to, etc.
600
601 \begin{lstlisting}[language=C]
602 // Extension functions *must* be static and convention is to use names that start with `f_'
603 static naRef f_demo(naContext ctx, naRef me, int argc, naRef* args)
604 {
605 // Write your C code here
606 return naNil();
607 }
608 \end{lstlisting}
609
610 \section{The Main Nasal API in C}
611 All of the C API is included in the \nasalsourcefile{nasal.h} file, which in turn gets included by every module or application wanting to use Nasal. It includes the type-specific manipulation functions shown above along with all of the types (\type{naRef}, \type{naPtr}, etc.) and other parts of the API.
612
613 %\subsection{String Implementation}
614 %\subsection{Vector Implementation}
615 %\subsection{Hash Implementation}
616
617 \section{How to Create an API}
618 \section{Using CPPBind}
619 Also see: \url{http://wiki.flightgear.org/Nasal/CppBind}.
620
621 C++Bind is a really cool API for interfacing with Nasal through C++ classes, methods, and advanced STL functionality.
622
623 \part{Internals: Parsing through Running}
624 \comment{
625 \section{Code Generation Steps}
626
627 \todo{use different block styles for FILE/PROGRAM input, parser, codegen, VM ?}
628 % Define block styles
629 \tikzstyle{block} = [rectangle, draw, fill=blue!20, text width=5em, text centered, rounded corners, minimum height=4em]
630 \tikzstyle{line} = [draw, -latex']
631
632 % see http://www.texample.net/tikz/
633
634 \begin{tikzpicture}[node distance = 2cm, auto]
635
636 % Place nodes
637 \node [block] (source) {Source Code};
638 \node [block, below of=source] (tokenizer) {Tokenize};
639 \node [block, below of=tokenizer] (parser) {Parse};
640 \node [block, below of=parser] (codegen) {Generate Code};
641 \node [block, below of=codegen] (vm) {Run Code (VM)};
642 \node [block, right of=vm] (GC) {Garbage Collector (GC)};
643
644 % Draw edges
645 \path [line] (source) -- (tokenizer);
646 \path [line] (tokenizer) -- (parser);
647 \path [line] (parser) -- (codegen);
648 \path [line] (codegen) -- (vm);
649 \path [line] (vm) -- (GC);
650
651 \end{tikzpicture}
652 }
653
654 \section{Overview of Parsing}
655 ``Parsing'' a file involves a many-tiered hierarchy of transformations that results in a piece of executable code stored in a newly-allocated \type{naCode} object. This is essentially what a Nasal \nasalkeyword{func}\{$\langle$\textit{contents of file}$\rangle$\} expression would do, but of course it is through parsing files that function expressions can be generated, not the other way around.
656
657 Parsing of a script starts out in \nasalsourcefile{parse.c}, the Nasal parser, which initializes a new parse object (\type{struct Parser} {\tt p}) and then runs the string through the lexer, via \func{naLex}\fp\ \citesourcefile[338]{lex.c}, generating list of ``tokens'' that represent each lexeme (builtin Nasal keyword/operator), symbol, and constant. This then is returned to \nasalsourcefile{parse.c}, which runs a block parser over the tokens, adding tree structure ``up'' and ``down''. After this the precedence,,,,,,, parser goes throuhin blocks and transforms them into a structured representation of operations. This list, though still made of tokens, represents a more abstract view of the expression that is being parsed, but in a form that is easier for the code generation to understand due to the fact that operators are tightly connectected with their often complex operands. Finally, the expression list is given to \func{naCodeGen}\fp\ \citesourcefile[702]{codegen.c}, which takes the tokens and creates opcodes -- low-level instructions that will later be executed by the Nasal Virtual Machine each time the function is called. The code object (as returned by \func{naCodeGen}) is then returned from \func{naParseCode}\fp, to be saved to a \type{naCode} object or, by extension, a \type{naRef} referencing such.
658
659 \subsection{Lexing}
660 \todo{maybe split this, i.e. general section on parsing, with all steps, tokenize, lexing, parse tree generation? Also, parsing can be visualized using tikz graphs with left-hand and right-hand tokens, VM stuff should be introduced after parsing probably}
661
662 ``Lexing'' is the process of converting a stream of characters (which is hard for a computer to directly read) to a series of objects (\type{structs} in C) that are easier for a computer understand. In Nasal, a string is made into a linked list of \type{struct Tokens}, each of which can represent either a ``lexeme'' (a symbol that has special meaning in Nasal, like `+=') or some other type of token, like a string or numeric literal, or a symbol. Each \type{Token} can store a string and its length or a double in addition to its type (\Tok{Literal}, etc.) and its line number.
663
664 \subsection{Block and Precedence Parser}
665 \textit{[Note: for this section, I can do a good job of explaining how the algorithms work in an abstract manner, but if you want to understand how the C functions fit together to do this work or learn what exactly is done, then I recommend reading through the relevant functions in \nasalsourcefile[238]{parse.c} (\textcolor{func}{precChildren}, \textcolor{func}{precBlock}, and \textcolor{func}{parsePrecedence}); it really isn't a difficult task and will set you up for being able to understand the algorithm and modify it ---end note]}
666
667 The first job that \nasalsourcefile{parse.c} does is create the tree of tokens with regard to adding ``blocks''. Some tokens open a block and have a matching ending token; namely parentheses (`(' and `)'), brackets (`[' and `]'), and curly braces (`\{' and `\}'). When the block parser comes upon an opening token, it parses succesive tokens into children of the opening one until it finds an ending one. If another opening brace is encountered, another block parser parses that and gets to use up the tokens in the stream until its block has ended, which then returns control back to the previous block parser at the token after the ending one. A parse error occurs if a closing brace is encountered that does not match the token that started the block or if the parse finds the end of the file without encountering a suitable ending token. Aside from matching pairs, blockoids (\textcolor{keyword}{if}/\textcolor{keyword}{elsif}/\textcolor{keyword}{else}, \textcolor{keyword}{for}/\textcolor{keyword}{while}, \textcolor{keyword}{func}, etc.) are also parsed at this stage. Parts of the blockoid structure (parethesis as "arguments" to the loopoid, braces or braceless bodies, and extra else/elsif's after an if) get put as children of the blockoid token. Parethesis and braces obviously get parsed by the previously described system, and a braceless body gets parsed by a special one which looks for a semi-colon, miscellaneous end-of-block (like an extra closing parenthesis or even an else token), or end of the file. The middle condition allows the end-of-block to be parsed at a higher level. Consider this Nasal statement:
668
669 \begin{lstlisting}[language=nasal]
670 setlistener("/sim/foo", func print("activated"));
671 \end{lstlisting}
672
673 The function body parser reads ``print'', then a matching pair of parentheses, and finds a closing parenthesis. This parenthesis looks out of place, but it actually belongs to the token after setlistener, so to allow the parse to succeed the extra parenthesis must be declared as one-past-end-of-block and be the next token the parent parser sees -- which will successfully end the block since they match.
674
675 Anyways, a blockoid construct ends up with potentially three children: a parenthesized argument list, a body with braces or without (braceless bodies end up as children of a \Tok{Brace}, so the body always has braces going into the next phase of parsing), and if the blockoid is an ``if'' then it can have an else or elsif as its last child.
676
677 The next part of parsing is one of the most fun ones. The precedence parser creates a binary tree out of the blocks of tokens that were previously generated. There are three transformations that this parser can handle: \Prec{Binary}/\linebreak[0]\Prec{Reverse}, \Prec{Prefix}/\linebreak[0]\Prec{Suffix}, and no precedence (single token). \Prec{Binary} and \Prec{Reverse} are opposites; same with \Prec{Prefix} and \Prec{Suffix}. The main point of precedence parsing is to break a long stream of tokens into a binary tree with a large expression formed by an operator and optional expressions on either side. Each unary or binary operator is given a precedence label at the top of parse.c. That table in order of parse-first--parse-last is as follows:
678 \\
679 \begin{longtable}{| r || l | l | l |}
680 \hline
681 \bf{Precedence:} & \bf{Token(s):} & & \endhead
682 \hline
683 \PREC{REVERSE} & \TOK{SEMI} & \TOK{COMMA} & \\
684 \hline
685 \PREC{SUFFIX} & \TOK{ELLIPSIS} & & \\
686 \hline
687 \PREC{PREFIX} & \TOK{RETURN} & \TOK{BREAK} & \TOK{CONTINUE} \\
688 \hline
689 \PREC{REVERSE} & \TOK{ASSIGN} & \TOK{PLUSEQ} & \TOK{MINUSEQ} \\
690 & \TOK{MULEQ} & \TOK{DIVEQ} & \TOK{CATEQ} \\
691 \hline
692 \PREC{REVERSE} & \TOK{COLON} & \TOK{QUESTION} & \\
693 \hline
694 \PREC{PREFIX} & \TOK{VAR} & & \\
695 \hline
696 \PREC{BINARY} & \TOK{OR} & & \\
697 \hline
698 \PREC{BINARY} & \TOK{AND} & & \\
699 \hline
700 \PREC{BINARY} & \TOK{EQ} & \TOK{NEQ} & \\
701 \hline
702 \PREC{BINARY} & \TOK{LT} & \TOK{LTE} & \TOK{GT} \\
703 & \TOK{GTE} & & \\
704 \hline
705 \PREC{BINARY} & \TOK{PLUS} & \TOK{MINUS} & \TOK{CAT} \\
706 \hline
707 \PREC{BINARY} & \TOK{MUL} & \TOK{DIV} & \\
708 \hline
709 \PREC{PREFIX} & \TOK{MINUS} & \TOK{NEG} & \TOK{NOT} \\
710 \hline
711 \PREC{SUFFIX} & \TOK{LPAR} & \TOK{LBRA} & \\
712 \hline
713 \PREC{BINARY} & \TOK{DOT} & & \\
714 \hline
715 \end{longtable}
716
717 When the precedence parser gets run, it starts at the top row, and if a condition is fullfilled, then the linked-list of Tokens is split into top (the matching token), left, and right (which are added as the binary children of top, or 0 if there is none to add). The left and right tokens are binary trees formed by extra calls to the precedence parser, with four different rules according the the precedence type. The prefix/suffix operators are simple: they are only recognized at the beggining (if prefix) or end (if suffix) of the list. The tokens from the one inside of the matching token to the end of the opposite side are parsed as either the left or right child (this is right for prefix, left for suffix). Any children are precedence parsed as well and added on the other side, or 0 if there are no children. (Note: children are only going to be present on parentheses or brackets in the role of a suffix operator.)
718
719 Binary and reverse operators are a bit different: they can occur anywhere \emph{but} the endcaps (not the start token, not the end one, but anywhere in between). For binary operators, the rightmost one is grabbed, and vice-versa for reverse operators. (The way I remember this is that the statement separator (;) is a reverse, but the top of the list of them is going to be the leftmost ones; thus binary operators must have the top be the rightmost one, opposite of reading order.) All the tokens from the start to one left of the operator is parsed as the left child, and similarly for the right child. One side is parsed at the same precedence (because there might be more of the same precedence level that lie undiscovered) and the other is parsed at the next precedence level.
720
721 If the parser reaches a state where the end and start of the list are the same, then that token is added to the tree as either a leaf (if it has no children) or another branch (with both left and right pointers pointing to the top of the precedence-parsed tree formed from its children). The end result of this sorting is a tree of tokens, where each may have 0, 1, 2, or duple children (duple meaning that both children are the same, which is true in the last case we discussed). This tree for an example file looks something like this:
722
723 \todo{ this should probably be a new tex function to create parse trees for Nasal expressions and visualize them accordingly, i.e. enable parser debugging to get a console dump (WIP!) }
724
725 \begin{lstlisting}[language=nasal]
726 var x = 1.5 - 0.5;
727 \end{lstlisting}
728
729 \begin{lstlisting}
730 // Notation:
731 // Prefix Name = value (Precedence)
732 // Prefix:
733 // l Left child
734 // r Right child
735 // b Both children (left == right)
736 // . (Spacer)
737 // Precedence: what rule was used to parse
738
739 TOP (Synthetic)
740 b SEMI (Reverse)
741 . l ASSIGN (Binary)
742 . . l VAR (Prefix)
743 . . . r SYMBOL = x (None)
744 . . r MINUS (Binary)
745 . . . l LITERAL = 1.5 (None)
746 . . . r LITERAL = 0.5 (None)
747 . r EMPTY (Synthetic)
748 \end{lstlisting}
749
750 \comment{
751 %\tikzstyle{vertex}=[draw,fill=black!15,circle,minimum size=20pt,inner sep=0pt]
752 \tikzstyle{vertex}=[draw,fill=black!15,minimum size=20pt,inner sep=0pt]
753
754 \begin{tikzpicture}[font=\sffamily,thick,level/.style={sibling distance=50mm/#1}]
755 \node[vertex] {TOK\_SEMI}
756 child {
757 node[vertex] {TOK\_ASSIGN}
758 child {
759 node[vertex] {TOK\_VAR}
760 }
761 }
762 child {
763 node[vertex] {TOK\_SYMBOL}
764 };
765 \end{tikzpicture}
766 %\comment{
767 \\\\ %blank lines
768 %\begin{tikzpicture}[font=\sffamily,thick,level/.style={sibling distance=50mm/#1}]
769 \begin{tikzpicture}[font=\sffamily,thick,level/.style={sibling distance=100mm/#1}]
770 \node[vertex] {TOK\_TOP}
771 child {
772 node[vertex] {TOK\_SEMI}
773 child {
774 node[vertex] {TOK\_ASSIGN}
775 child {
776 node[vertex] {TOK\_VAR}
777 }
778 child {
779 node[vertex] {TOK\_MINUS}
780 child {
781 node[vertex] {TOK\_LITERAL\\1.5}
782 }
783 child {
784 node[vertex] {TOK\_LITERAL\\0.5}
785 }
786 }
787 }
788 child {
789 node[vertex] {TOK\_EMPTY}
790 }
791 };
792 \end{tikzpicture}
793 \\\\
794 \begin{tikzpicture}[font=\sffamily,thick,level/.style={sibling distance=50mm/#1}]
795 %\tikzset{text width=5.8em, text centered}
796 \tikzset{every tree node/.append style={draw}}
797 \Tree [.\Token{TOP}
798 \edge node[auto=right]{\func{LEFT}\fp}; \Token{SEMI}
799 %\leftToken{SEMI}
800 \Token{OTHER}
801 \edge node[auto=left]{\func{RIGHT}\fp}; \Token{SEMI}
802 %\leftToken{SEMI}
803 ]
804 \end{tikzpicture}%}
805
806 % Currently we cannot fit much here...
807 \begin{tikzpicture}
808 \tikzset{level distance=40pt, sibling distance=6pt, text width=5.8em, text centered}
809 \tikzset{every tree node/.append style={draw}}
810 \tikzstyle{every node}=[font=\small]
811 \Tree [.{{\sc Tok\_Top}}
812 [.{{\sc Tok\_Semi}}
813 [.{{\sc Tok\_Assign}}
814 the
815 ]
816 [.{{\sc Tok\_Literal} (value: 1.5)} cat ]
817 ]
818 [.{{\sc Tok\_Semi}}
819 [.{{\sc Tok\_Assign}}
820 the
821 ]
822 [.{{\sc Tok\_Todo} (value: 1.5)} cat ]
823 ]
824 ]
825 \end{tikzpicture}
826 }
827
828 \section{Code Generation -- producing bytecode}
829
830 Code generation is the next step of parsing and is implemented in the file \nasalsourcefile{codegen.c}. It takes the expression tree generated by the lexer and \nasalsourcefile{parse.c} recursively traverses it to create opcodes -- little ``numbers'' (or an \type{enum}) that are interpreted by the Nasal Virtual Machine as instructions. With the exception of blockoids (which have a slightly different structure with up to three children), the token structure that code generation gets is a tree where the most important (highest precedence) tokens are on top, and tokens of lesser- and equal-importance tokens on the sides; laws of grouping are followed as well (like parenthesis and such) by having both left and right children point to the top of the tree for the expression inside of the block.
831
832 The example above shows what is really neat about this approach: when it is parsing, say, an assignment operator ($=$), it knows that the left side is going to be a symbol and that the right side can be any type of expression. Seeing it this way makes much more sense then first seeing the symbol, looking ahead for an assignment, and then hoping the rest of the tokens parse correctly -- that would be a more text-based approach and it is not scalable for complicated syntaxes with oodles of operators with different semantics.
833
834 The method used in \nasalsourcefile{parse.c} allows for the minimal-step, maximally-recursive code generator present in Nasal: parsing a mathematical operator is as simple as generating the left and right expressions, and then emitting the correct VM instruction afterwards -- the function handling the mathematical operator does not need to know what lives below the operator, only that it exists. Each step of the generator (implemented in the \nasalapi{gen\br Expr} function and surrounding static functions) takes the smallest step it can and lets the parse tree work itself out by calling helper functions to handle expressions and expression lists.
835
836 Local macros helping with abstraction include:
837
838 \begin{enumerate}
839 \item \localmacro{LEFT(tok)} to get the left-hand branch of a token (i.e. \verb$tok->children$).
840 \item \localmacro{RIGHT(tok)} to get the right hand branch of a token (i.e. \verb$tok->lastChild$).
841 \item \localmacro{BINARY(tok)} to check if a token is a binary expression (if there is only two children: \verb$tok->children$ and \verb$tok->lastChild$, and nothing in between, meaning that they reference each other in their \name{next/prev} members).
842 \end{enumerate}
843
844 The low-level workhorses of the code generator are the \nasalapi{emit}\fp\ and \nasalapi{emit\br Immediate}\fp\ functions, which directly write bytecode into the parser structure's codegen pointer.
845
846 \begin{lstlisting}[language=C]
847 static void emit(struct Parser* p, int val)
848 {
849 // Reallocate if necessary
850 if(p->cg->codesz >= p->cg->codeAlloced) {
851 int i, sz = p->cg->codeAlloced * 2;
852 unsigned short* buf = naParseAlloc(p, sz*sizeof(unsigned short));
853 for(i=0; i<p->cg->codeAlloced; i++) buf[i] = p->cg->byteCode[i];
854 p->cg->byteCode = buf;
855 p->cg->codeAlloced = sz;
856 }
857 // And add our next opcode
858 p->cg->byteCode[p->cg->codesz++] = (unsigned short)val;
859 }
860 \end{lstlisting}
861
862 \begin{lstlisting}[language=C]
863 static void emitImmediate(struct Parser* p, int val, int arg)
864 {
865 emit(p, val);
866 emit(p, arg);
867 }
868 \end{lstlisting}
869
870 This ``immediate'' value is associated with the opcode and retrieved later in the VM stage. In general it is just an \type{unsigned short}, but it can mean several things.
871
872 Some immediate-mode opcodes refer to the constants table -- this is a chunk in the \type{naCode} which holds scalar constants (string/numeric literals) and code constants (\nasalkeyword{func}\{\} blocks in the code). These opcodes always need the constants index added when \nasalapi{emit\br Imme\-diate}\fp\ is called, using either \nasalapi{find\br Constant\br Index}\fp\ or a precomputed index, such as returned from \nasalapi{new\br Constant}\fp. Of this type, there are only these three:
873 \begin{enumerate}
874 \item \OP{PUSHCONST}
875 \item \OP{MEMBER}
876 \item \OP{LOCAL}
877 \end{enumerate}
878
879 In addition, these two use their immediate value to represent their number of arguments; this is because the VM needs to be able to pop the right amount of arguments from the operand stack:
880 \begin{enumerate}
881 \item \OP{FCALL}
882 \item \OP{MCALL}
883 \end{enumerate}
884
885 And lastly, branching instructions are also immediate-mode; their immediate value refers to the index of the command to jump to. The specific opcodes are:
886 \begin{enumerate}
887 \item \OP{JIFTRUE}
888 \item \OP{JIFNOT}
889 \item \OP{JIFNOTPOP}
890 \item \OP{JIFEND}
891 \item \OP{JMP}
892 \item \OP{JMPLOOP}
893 \end{enumerate}
894
895 When jumping backwards, the address is saved away earlier and emmitted with the \Op{Jmp} instruction, but when jumping forwards, the code it is jumping to does not exist yet and therefore its index is not known. To get around that, there are some functions to handle forward-jumps. \nasalapi{emit\br Jump} makes a new jump with a dummy index:
896
897 \begin{lstlisting}[language=C]
898 // Emit a jump operation, and return the location of the address in
899 // the bytecode for future fixup in fixJumpTarget
900 static int emitJump(struct Parser* p, int op)
901 {
902 int ip;
903 emit(p, op);
904 ip = p->cg->codesz;
905 emit(p, 0xffff); // dummy address
906 return ip;
907 }
908 \end{lstlisting}
909
910 As suggested by the comment, \nasalapi{fix\br Jump\br Target} is what comes along at the desired jump-to point and adds in the correct index:
911
912 \begin{lstlisting}[language=C]
913 // Points a previous jump instruction at the current "end-of-bytecode"
914 static void fixJumpTarget(struct Parser* p, int spot)
915 {
916 p->cg->byteCode[spot] = p->cg->codesz;
917 }
918 \end{lstlisting}
919
920 For typical usage, here's a stripped down \nasalapi{gen\br If} example:
921
922 \begin{lstlisting}[language=C]
923 static void genIf(struct Parser* p, struct Token* tif, struct Token* telse)
924 {
925 int jumpNext, jumpEnd;
926 genExpr(p, tif->children); // the test
927 jumpNext = emitJump(p, OP_JIFNOTPOP);
928 genExprList(p, tif->children->next->children); // the body
929 jumpEnd = emitJump(p, OP_JMP);
930 fixJumpTarget(p, jumpNext);
931 if(telse) {
932 if(telse->type == TOK_ELSIF) genIf(p, telse, telse->next);
933 else genExprList(p, telse->children->children);
934 } else {
935 emit(p, OP_PUSHNIL);
936 }
937 fixJumpTarget(p, jumpEnd);
938 }
939 \end{lstlisting}
940
941 The first jump points to right after the second jump, since \nasalapi{fix\br Jump\br Target} is called after \nasalapi{emit\br Jump} is called the second time. After the \nasalkeyword{else}\{\} clause is handled, the second jump is made to point after all of that. The power in this is allowing arbitrary chunks of code (e.g. as emitted from \nasalapi{gen\br Expr\br List}) to be jumped over.
942
943 \subsection{Initialization}
944
945 Code generation itself is started in \nasalapi{na\br Code\br Gen}\fp\ where the code generation related data structures are allocated and initialized, including:
946
947 \begin{enumerate}
948 \item an \type{naCode}* code object
949 \item argument list processing
950 \end{enumerate}
951
952 Afterwards, \nasalapi{gen\br Expr\br List}\fp\ is invoked, which in turn recursively invokes itself and \nasalapi{gen\br Expr}\fp\ while traversing the semi-colon-seperated statements in the parse tree, the latter is the primary workhorse of the code generator in that it will recognize and turn tokens into bytecode primitives.
953
954 \subsection{Constants Table}
955
956 This stores constants used in a function's body, both scalars and code. Implemented during codegen as a \type{naVec} for the purposes of cheap alloc handling, this gets turned into a static table as part of the \type{naCode} structure. \nasalapi{internConstant}\fp\ is used to return a reference to the existing constant if one already exists; it relies on \nasalapi{newConstant}\fp\ to add the constant if needed. Code for both (in reverse order of declaration):
957
958 \begin{lstlisting}[language=C]
959 // Interns a scalar (!) constant and returns its index
960 static int internConstant(struct Parser* p, naRef c)
961 {
962 int i, n = naVec_size(p->cg->consts);
963 if(IS_CODE(c)) return newConstant(p, c);
964 for(i=0; i<n; i++) {
965 naRef b = naVec_get(p->cg->consts, i);
966 if(IS_NUM(b) && IS_NUM(c) && b.num == c.num) return i;
967 else if(IS_NIL(b) && IS_NIL(c)) return i;
968 else if(naStrEqual(b, c)) return i;
969 }
970 return newConstant(p, c);
971 }
972
973 static int newConstant(struct Parser* p, naRef c)
974 {
975 int i;
976 naVec_append(p->cg->consts, c);
977 i = naVec_size(p->cg->consts) - 1;
978 if(i > 0xffff) naParseError(p, "too many constants in code block", 0);
979 return i;
980 }
981 \end{lstlisting}
982
983 \section{The Code Generation API}
984 \todo{document the codegen.c APIs?}
985
986 \section{Code Generation Examples}
987 \todo{discuss loops, function calls, methods?}
988
989 \section{Virtual Machine: running code}
990 As mentioned before, the Nasal bytecode gets executed in \nasalsourcefile{code.c} using an infinite interpreter loop with a huge switch/case block in the form of the \func{run}\fp\ function in \nasalsourcefile{code.c}. This is the ``Virtual Machine'' (VM) of Nasal. In general, machines take some form of operations (e.g. Nasal bytecode) and execute them based upon other factors, like other inputs, and then produce an output of some kind. (A \emph{virtual} machine is simply such a machine that is implemented in software not hardware -- e.g. C/C++ code versus circuit boards). Some of the simplest machines are stack machines; this is what is used for the Nasal VM, stack machines are generally a popular concept, and e.g. also used by Java. The Nasal stack machine uses two main stacks and \emph{pushes} and \emph{pops} from those stacks. Each stack is an array of variables with a fixed size -- exceeding this size is an error. The first stack is where all the opcodes are stored and it is for all purposes of type \type{unsigned short} or \type{int}, since each opcode is part of an enumeration. This also allows other integers to live on the stack as well (more on this later). The other stack is made up of \type{naRefs}, which are the ``operands'' that the opcodes operate on.
991
992 For most typical opcodes, the VM pops some arguments from the stack -- that is, it takes the top item on the stack and saves it to a variable if needed, then it decrements the top of the stack so that the popped argument ``disappears'' from the stack. After performing the operation, the VM will push a result back onto the stack -- this does the opposite of popping as it increments the top of the stack and sets the new top item. Thus pushing makes a ``new'' item on the top of the stack while popping takes one away. Eventually this change in state cascades down as a result of operations and a useful output is acheived. While the Nasal VM can do a fair amount of variable-handling operations on its own, \type{naCFunctions} can add more operations (e.g. \func{f\_setsize}\fp) or can provide access to anything accessible from C space, like \func{f\_print}\fp\ and the io library do.
993
994 These two stacks live in different places. The opcode stack lives in the \type{naCode} object under the constants block and is extracted using the \globalmacro{BYTECODE}\fp\ macro defined in \nasalsourcefile{data.h}, which typecasts the \type{naRef} to an \type{unsigned short}* (see \nasalsourcefile[147]{data.h}, line 147). The ``cursor'' for the bytecode is stored in the current frame's \name{ip} member. A common operation is then \type{int} \verb$op = $\func{BYTECODE}\verb$(cd)[f->ip++];$ (which is used in \nasalsourcefile{code.c} to retrieve the opcode and/or an argument, implicitly typecasting to an integer). By this method, the opcode ``stack'' is not a ``true'' stack in the fact that it is immutable (should {\bf not} be changed except using stack operations like push/pop!) and can only move one direction (adds to it during code generation, moves down it during the running of the code). The other stack -- the one of \type{naRefs} -- is actually a real stack. The items are stored in the context's \name{opStack} member, which has \localmacro{MAX\_STACK\_DEPTH} number of terms, and its cursor is stored in the \name{opTop} member. Note that indexing \name{opStack} with the current \name{opTop} index is not a valid operation -- the true top item on the stack is one below is at \verb$STK(1)$ or \verb$ctx->opTop-1$. There are various helper macros to help out with operations on this stack, like \func{PUSH}\fp\ and \func{POP}\fp\ and in particular \localmacro{STK(n)}, which directly retrieves an item on the stack (where $n=1$ is the top member as previously mentioned, and $n=2$ is the second, etc.). Note that the \func{STK}\fp\ macro requires manual movement of the \name{opTop} index, i.e. the programmer has to use \verb$ctx->opTop--$ or \verb$ctx->opTop-=2$. For more info, see code.c, line 246 for \func{PUSH}\fp, and lines 520--523 for the other macros.
995
996 Also, there are two other relevant stacks. The first one is the stack of frames. Since a function can be called in an overlapping fashion (e.g. a function calling itself recursively, or being called in a multithreaded fashion from different threads), Nasal needs separate places to store information for each separate call. This stack is made up of \type{struct Frames} and lives in the \name{fStack} member, which has size of \localmacro{MAX\_RECURSION}, and its index is in the \name{fTop} member. New calls are pushed in at the \name{fTop} index and the current frame is \verb$ctx->fStack[ctx->fTop-1]$ while the first frame is \verb$ctx->fStack[0]$.
997
998 \subsection{An example}
999 To take an example of the VM in action, let's say that we execute this Nasal statement:
1000
1001 \begin{lstlisting}[language=nasal]
1002 var foo = 1.5-0.5;
1003 \end{lstlisting}
1004
1005 This takes and sets the local variable ``foo'' with the result of 1.5 minus 0.5 (code generation does not optimize any). This would produce a stack of opcodes like this:
1006
1007 \todo{all these examples are neat and important, but tedious and error-prone to create: we should automate the creation of them using our Nasal/LaTex hacks, so that we can dump the stacks to the console and even turn them into nice "stack tables" to be used here}
1008
1009 \begin{verbatim}
1010 Stack of op codes: Stack of arguments:
1011 [start] ... ctx->opTop
1012 OP_PUSHCONST [end]
1013 00003
1014 OP_PUSHCONST
1015 00004
1016 OP_MINUS
1017 OP_PUSHCONST
1018 00005
1019 OP_SETLOCAL
1020 ...
1021 OP_RETURN
1022 \end{verbatim}
1023
1024 The first two opcodes are \Op{Pushconst}s, which take a constant and pushes it onto the (previosuly empty) stack at the top. This illustrates the fact that each function call starts with a clean stack of operands, and all constants have to be initialized. This particular one points to constant `3', which should hold an \type{naRef} with it's number set to 0.5. Then we push another number, which will be 1.5. Then we get this stack:
1025
1026 \begin{verbatim}
1027 Stack of op codes: Stack of arguments:
1028 ... ... ctx->opTop
1029 OP_MINUS naRef 1.5 STK(1)
1030 OP_PUSHCONST naRef 0.5 STK(2)
1031 00005 [end]
1032 OP_SETLOCAL
1033 ...
1034 OP_RETURN
1035 \end{verbatim}
1036
1037 The first opcode is \Op{Minus}, which takes the first argument (1.5) and subtracts the second (0.5) and places the result (1.0) where the second used to be, then decrements the top of the stack. The stack now looks like this:
1038
1039 \begin{verbatim}
1040 Stack of op codes: Stack of arguments:
1041 ... ... ctx->opTop
1042 OP_PUSHCONST naRef 1.0 STK(1)
1043 00004 [end]
1044 OP_SETLOCAL
1045 ...
1046 OP_RETURN
1047 \end{verbatim}
1048
1049 Now we see \Op{Pushconst} and a number after it. This push operation takes an argument of type \type{int} from the stack of opcodes, not \type{naRefs}, and retrieves the constant \type{naRef} stored at the specified index in the constants block of the currently executing code using the \localmacro{CONSTARG}\fp\ macro \citesourcefile[520]{code.c}. During code generation, this constant is saved away inside of the code's constant block for each required lvalue, and this opcode pushes the correct one onto the stack -- which should be a \type{naRef} representing ``foo'' and is pushed in before the result of the \Op{Minus}, setting us up for the next step:
1050
1051 \begin{verbatim}
1052 Stack of op codes: Stack of arguments:
1053 ... ... ctx->opTop
1054 OP_SETLOCAL naRef foo STK(1)
1055 ... naRef 1.0 STK(2)
1056 OP_RETURN [end]
1057 \end{verbatim}
1058
1059 We finally get to \Op{Setlocal}, which sets a local variable (i.e. one using the `var' keyword) to a value. It takes the first argument on the stack as the lvalue (symbolic name) of the variable and the second as the value to set it to. In this case, we see those are ``foo'' and 1, respectively, and so the variable foo correctly gets set to 1. Note that this operation does not explicitly ``return'' anything, i.e. it does not push a `result', but it does have the implicit return of the value set, since that is the last argument left on the stack (since the \Op{Setlocal} operation only moves down 1 on the stack). This illustrates an interesting feature of Nasal: it always has its current working state and every operation returns \emph{something}. We will see this in action in the next paragraph.
1060
1061 \begin{verbatim}
1062 Stack of op codes: Stack of arguments:
1063 ... ... ctx->opTop
1064 OP_RETURN naRef ?? STK(1)
1065 \end{verbatim}
1066
1067 We execute some more statements in between and eventually get to a return opcode -- this is required otherwise the Nasal VM will get stuck in an infinite loop and possibly do some very weird things. Anyways, sometimes this return is implicit and is synthesized by the code generation, if so it returns the first argument on the stack -- remember how we called it the ``current working state''? An equivalent expression that makes this return explicit goes like so:
1068
1069 \begin{lstlisting}[language=Nasal]
1070 return (...);
1071 \end{lstlisting}
1072
1073 Substitue the last expression you want to execute into the parentheses and you are set. A great mistake would be to say ``Oh, I just need to type return-$\langle$semicolon$\rangle$ and I'll be set.'' This is incorrect, since code generation makes an \Op{Pushnil} before any return statement like this:
1074
1075 \begin{lstlisting}[language=Nasal]
1076 return (...);
1077 \end{lstlisting}
1078
1079 Thus it would really return nil, not the last expression that was evaluated. See line 631 of \nasalsourcefile[631]{codegen.c} for more information.
1080
1081 \todo{we should generalize this, turn it into a command and use it as a template for LaTex-based stack diagrams that can be emitted from Nasal directly}
1082 \usetikzlibrary{shapes.multipart}
1083 \begin{tikzpicture}[stack/.style={rectangle split, rectangle split parts=#1,draw, anchor=center, fill=white}]
1084 \node[stack=5] {
1085 \nodepart{one}\OP{RETURN}
1086 \nodepart{two}...
1087 \nodepart{three}...
1088 \nodepart{four}...
1089 \nodepart{five}...
1090 };
1091 \end{tikzpicture}
1092
1093 \subsection{VM Operators/Opcodes}
1094 Here is a semi-comprehensive list of all the operators and their functions.
1095
1096 \subsubsection{Unary operators}
1097 Operators that modify STK(1) in place:
1098 \begin{description}
1099 \item \OP{NOT} \label{op:NOT}\label{op:Not} Boolean inverse (i.e. \verb$!a$, $\neg a$).
1100 \item \OP{NEG} \label{op:NEG}\label{op:Neg} Additive inverse (i.e. \verb$-a$, $-a$).
1101 \end{description}
1102
1103 \subsubsection{Binary operators}
1104 Operators that pop two arguments and push a result:
1105 \begin{description}
1106 \item \OP{PLUS} \label{op:PLUS} \label{op:Plus} Addition (i.e. \verb$a+b$, $a + b$).
1107 \item \OP{MINUS}\label{op:MINUS}\label{op:Minus} Subtraction (i.e. \verb$a-b$, $a - b$).
1108 \item \OP{MUL} \label{op:MUL} \label{op:Mul} Multiplication (i.e. \verb$a*b$, $a\times b$).
1109 \item \OP{DIV} \label{op:DIV} \label{op:Div} Division (i.e. \verb$a/b$, $a\div b$).
1110 \item \OP{CAT} \label{op:CAT} \label{op:Cat} Concatenate either two vectors or two strings (i.e. \verb$a~b$).
1111 \item \OP{LT} \label{op:LT} \label{op:Lt} Strictly less-than (i.e. \verb$a<b$, $a < b$).
1112 \item \OP{GT} \label{op:GT} \label{op:Gt} Strictly greater-than (i.e. \verb$a>b$, $a > b$).
1113 \item \OP{LTE} \label{op:LTE} \label{op:Lte} Less-than-or-equal-to (i.e. \verb$a<=b$, $a\leq b$).
1114 \item \OP{GTE} \label{op:GTE} \label{op:Gte} Greater-than-or-equal-to (i.e. \verb$a>=b$, $a\geq b$).
1115 \item \OP{EQ} \label{op:EQ} \label{op:Eq} Equality or equivalence (i.e. \verb$a==b$, $a\equiv b$; tests for numerical esuality if possible and acts recursively on hashes and vectors besides comparing pointers).
1116 \item \OP{NEQ} \label{op:NEQ}\label{op:Neq} Non-equality/equivalence (i.e. \verb$a!=b$, $\neg(a\equiv b)$).
1117 \end{description}
1118
1119 \subsubsection{Push and/or pop operations}
1120 Operations that push or pop a \type{naRef} directly from the stack:
1121 \begin{description}
1122 \item \OP{POP} \label{op:POP} \label{op:Pop} Pop one \type{naRef} off of the stack (actually, it just moves the top of the stack down one).
1123 \item \OP{DUP} \label{op:DUP} \label{op:Dup} Push a duplicate of the top item.
1124 \item \OP{DUP2}\label{op:DUP2}\label{op:Dup2} Push duplicates of the top two items (e.g. $a, b$ becomes $a', b', a, b$).
1125 \item \OP{PUSHONE} \label{op:PUSHONE}\label{op:Pushone} Push a \type{naRef} `1'.
1126 \item \OP{PUSHZERO} \label{op:PUSHZERO}\label{op:Pushzero} Push a \type{naRef} `0'.
1127 \item \OP{PUSHNIL} \label{op:PUSHNIL}\label{op:Pushnil} Push a \func{naNil}\fp.
1128 \item \OP{PUSHEND} \label{op:PUSHEND}\label{op:Pushend} Push an \func{endToken}\fp.
1129 \item \OP{PUSHCONST}\label{op:PUSHCONST}\label{op:Pushconst} Take an integer argument from the {\bf opcode} stack then retrieve and push the constant found at that index in the code's constants block. See the \globalmacro{CONSTARG}\fp\ macro, line 520 in \nasalsourcefile[520]{code.c}, for more details. Also note that if the constant is a \type{naCode} object (inside of its \type{naRef} shell), then it gets bound to the current context/frame via \func{bindFunction}\fp\ (which turns it into a \type{naFunc}).
1130 \item \OP{NEWVEC} \label{op:NEWVEC}\label{op:Newvec} Push a new vector.
1131 \item \OP{NEWHASH} \label{op:NEWHASH}\label{op:Newhash} Push a new hash.
1132 \end{description}
1133
1134 \subsubsection{Jump operations}
1135 \todo{should this be renamed BRANCHING and should we differentiate here between unconditional and conditional branching ?}
1136 Operations that jump within either stack:
1137 \begin{description}
1138 \item \OP{JMP} \label{op:JMP}\label{op:Jmp} Execute a non-conditional jump to the bytecode index specified by the next item on the opcode stack (i.e. an integer one).
1139 \item \OP{JMPLOOP}\label{op:JMPLOOP}\label{op:Jmploop} Same, but execute \func{naCheckBottleneck}\fp\ first.
1140 \item \OP{JIFTRUE}\label{op:JIFTRUE}\label{op:Jiftrue} Jump if the top \type{naRef} on the stack is true. Does {\it not} pop from the stack!
1141 \item \OP{JIFNOT} \label{op:JIFNOT}\label{op:Jifnot} Same, but jumps if false.
1142 \item \OP{JIFNOTPOP}\label{op:JIFNOTPOP}\label{op:Jifnotpop} Same as \Op{Jifnot} but \emph{does} pop from the stack.
1143 \item \OP{JIFEND} \label{op:JIFEND}\label{op:Jifend} Jumps if the top \type{naRef} is an \func{endToken}\fp\ (i.e. the pointer equals \verb$($\type{void}*\verb$)1$). Pops only if it is an \func{endToken}\fp.
1144 \item \OP{MARK} \label{op:MARK}\label{op:Mark} Pushes a mark (the current size of the \type{naRef} stack) onto the mark stack.
1145 \item \OP{UNMARK} \label{op:UNMARK}\label{op:Unmark} Pops off a mark and discards it.
1146 \item \OP{BREAK} \label{op:BREAK}\label{op:Break} Takes and restores a mark position.
1147 \item \OP{BREAK2} \label{op:BREAK2}\label{op:Break2} Same, but pops it off instead of leaving it.
1148 \end{description}
1149
1150 \subsubsection{Function calls}
1151 These opcodes either call a \type{naCCode} or push another stack frame for a \type{naCode} call. The number of arguments is compiled during code generation and is thus fixed. By default, the top \name{nargs} on the stack are used as the arguments, another \type{naRef} is popped off as the function, and for method calls, another is popped off for the `me' reference. For named arguments, there is only 1 argument that is taken from the stack, which becomes the \name{locals} hash for the new frame, otherwise the \name{locals} are made by the \func{setupArgs}\fp\ function.
1152 \begin{description}
1153 \item \OP{FCALL} \label{op:FCALL}\label{op:Fcall} A basic function call.
1154 \item \OP{MCALL} \label{op:MCALL}\label{op:Mcall} A method call -- sets the `me' symbol.
1155 \item \OP{FCALLH}\label{op:FCALLH}\label{op:Fcallh} A function call with named arguments (the `H' is probably for ``hash-like'').
1156 \item \OP{MCALLH}\label{op:MCALLH}\label{op:Mcallh} A method call with named arguments.
1157 \end{description}
1158
1159 \subsubsection{Set methods}
1160 These methods set a variable and usually leave the value that was set on the stack, thus in most cases where you want to set something and don't care about the return, these should be followed by \Op{Pop}.
1161 \begin{description}
1162 \item \OP{SETLOCAL} \label{op:SETLOCAL}\label{op:Setlocal} Set the local variable named by STK(1) to the value given by STK(2).
1163 \item \OP{SETSYM} \label{op:SETSYM}\label{op:Setsym} Like \Op{Setlocal} but tries to find the variable in successive namespaces (i.e. each \verb$func->next$ in turn). If it is not found there, place it in the locals.
1164 \item \OP{SETMEMBER}\label{op:SETMEMBER}\label{op:Setmember} STK(1) is the name of the member, STK(2) is the hash, and STK(3) is the value.
1165 \item \OP{INSERT} \label{op:INSERT}\label{op:Insert} Like \Op{Setmember} but more generic for the case of vectors as well (i.e. \verb$hashvec[index]$ versus \verb$hash.member$).
1166 \item \OP{HAPPEND} \label{op:HAPPEND}\label{op:Happend} Another hash set but this time with the arguments in a funny order: STK(1) is the value to set, STK(2) the name, and STK(3) the hash.
1167 \end{description}
1168
1169 \subsubsection{Symbol ``get'' methods}
1170
1171 \begin{description}
1172 \item \OP{LOCAL} \label{op:LOCAL}\label{op:Local} Takes a constant argument and pushes
1173 \item \OP{MEMBER} \label{op:MEMBER}\label{op:Member} Retrieve a member from STK(1) with the name given by a \localmacro{CONSTARG}\fp. Recurses into the parents vector if necessary. This is unique -- no other function goes into the parents vector!
1174 \end{description}
1175
1176 \subsubsection{Miscellaneous}
1177 Other opcodes:
1178 \begin{description}
1179 \item \OP{XCHG} \label{op:XCHG}\label{op:Xchg} Swap the top two items on the stack.
1180 \item \OP{XCHG2} \label{op:XCHG2}\label{op:Xchg2} Swap the top three items on the stack (i.e. first becomes third and the two others get shifted `up' in the stack, thus a 1-2-3 order gets converted to a 2-3-1 order). An \Op{Xchg2} followed by an \Op{Xchg} results in a total reversing (i.e. 3-2-1) and \Op{Xchg} followed by an \Op{Xchg2} results in a swap of the lower two items (i.e. 1-3-2).
1181 \item \OP{EACH} \label{op:EACH}\label{op:Each} Works like a vector get: STK(1) is the index and STK(2) is the vector; it then increments the index and pushes the result.
1182 \item \OP{INDEX} \label{op:INDEX}\label{op:Index} Same, but pushes a copy of the index instead of the variable at that position in the vector.
1183 \item \OP{UNPACK} \label{op:UNPACK}\label{op:Unpack} Take the contents of the vector on the top of the stack and push its contents one-by-one for the number of times specified by the argument on the opccode stack.
1184 \item \OP{RETURN} \label{op:RETURN}\label{op:Return} If this is the top of the call stack (i.e. \name{fTop} is 1) then it returns from the \func{run}\fp\ function with the value of STK(1), else it resets to the next call up the stack setting the new STK(1) with the value of the old STK(1).
1185 \end{description}
1186
1187 \subsection{Stack Frames}
1188 Stack frames are essential to running a programming language. Functions call other functions, and their data must be stored on a stack. In Nasal, each \type{struct Context} object has a stack of frames in its \type{struct Frame} \name{fStack[]} member, whose top is stored in the \type{int} \name{fTop} member. The definition of each element is:
1189 \begin{lstlisting}[language=C]
1190 struct Frame {
1191 naRef func;
1192 naRef locals;
1193 int ip;
1194 int bp;
1195 };
1196 \end{lstlisting}
1197
1198 The \name{func} member stores the \type{naFunc} that created the Frame. The \name{locals} member is a new hash that is loaded with the arguments to the function and is used as the ``running namespace''; it is discarded when the function returns, unless saved by some means (either making a \nasalkeyword{func}\{\} that is findable by the GC or using the \func{caller}\fp\ API). Thus, despite many calls to the same function, especially in recursion, each invocation will safely run in its own, separate ``workspace'' and will not interfere with other calls of the same function. The \name{ip} and \name{bp} members refer to the position in the opcode (instruction pointer and base pointer) and \type{naRef} stacks, respectively. The former begins at 0 while the latter is equivalent to the \verb$ctx->opFrame$ at the time and is used to pop \verb$ctx->opFrame$ back to its old value, so that the function can access its own data on that stack again.
1199
1200 As a function call is executed, its frame is pushed onto the stack at the current \name{fTop} index, which is then pushed up one. Thus the frame of the currently executing code is \verb$ctx->fStack[ctx->fTop-1]$.
1201
1202 The relationship of of the operand stack with function calls is rather weird. All functions on a context's call stack end up using the same operand stack, and they all have access only to the top of it -- specifically they should only access those that they pushed themselves. When a function call is done, any of its data on the stack gets popped by setting \verb$ctx->$\br\verb$opFrame$\br\verb$ = $\br\verb$ctx->$\br\verb$fStack$\br\verb$[ctx->fTop$\br\verb$-1]$\br\verb$.bp$, its return gets pushed, and now the old function can use its old operands, with the return now added on top.
1203
1204 \comment{
1205 % stack frame example taken from: https://gitorious.org/tikz-goodies/tikz-goodies/blobs/0dffd069488fc812050e6ce5513736e83eaa666b/drawstack/stack-example.tex
1206 % also see: ftp://ftp.dante.de/tex-archive/macros/latex/contrib/drawstack/stack-example.pdf
1207 \todo {generalize this, style it for Nasal and then emit it directly via the interpreter}
1208 \begin{drawstack}
1209 \startframe
1210 \cell{First cell}
1211 \cell{Second cell}
1212 \finishframe{Some stack frame}
1213 \cell{Not interesting}
1214 \startframe
1215 \cell{Next stack frame}
1216 \cell{Next stack frame}
1217 \finishframe{Another stack frame}
1218 \end{drawstack}
1219
1220 \begin{enumerate}
1221 \item \url{http://stackoverflow.com/questions/10057443/explain-the-concept-of-a-stack-frame-in-a-nutshell}
1222 \item \url{http://www.cs.umd.edu/class/sum2003/cmsc311/Notes/Mips/stack.html}
1223 \item \url{http://en.wikibooks.org/wiki/X86_Disassembly/Functions_and_Stack_Frames}
1224 \item \url{http://en.wikipedia.org/wiki/Stack_frame#Structure}
1225 \item \url{http://www.dirac.org/linux/gdb/02a-Memory_Layout_And_The_Stack.php}
1226 \item \url{http://blog.morrisjohns.com/javascript_closures_for_dummies.html}
1227 \item \url {http://mark-story.com/posts/view/picking-up-javascript-closures-and-lexical-scoping}
1228 \end{enumerate}
1229 }
1230
1231 \todo{we can inspect stack frames using helpers in findFrame(), see naGetSourceFile() and naGetLine() for examples}
1232
1233 \section{Garbage Collection}
1234 \subsection{Mark \& Sweep}
1235 When using a mark-and-sweep collector, unreachable objects are not immediately reclaimed. Instead, garbage is allowed to accumulate until all available memory has been exhausted. When that happens, the execution of the program is suspended temporarily while the mark-and-sweep algorithm collects all the garbage. Once all unreferenced objects have been reclaimed, the normal execution of the program can resume.
1236
1237 Obviously, the main disadvantage of the mark-and-sweep approach is the fact that that normal program execution is suspended while the garbage collection algorithm runs. In particular, this can be a problem in a program that must satisfy real-time execution constraints (like a flight simulator). For example, an interactive application that uses mark-and-sweep garbage collection becomes unresponsive periodically.
1238
1239 The mark-and-sweep algorithm is called a tracing garbage collector because is traces out the entire collection of objects that are directly or indirectly accessible by the program. The objects that a program can access directly are those objects which are referenced by local variables on the processor stack as well as by any static variables that refer to objects. In the context of garbage collection, these variables are called the roots. An object is indirectly accessible if it is referenced by a field in some other (directly or indirectly) accessible object. An accessible object is said to be live. Conversely, an object which is not live is garbage.
1240
1241 The mark-and-sweep algorithm consists of two phases: In the first phase, it finds and marks all accessible objects. The first phase is called the mark phase. In the second phase, the garbage collection algorithm scans through the heap and reclaims all the unmarked objects. The second phase is called the sweep phase.
1242
1243 Nasal's implementation of \nasalapi{sweep}\fp\ (called \nasalapi{reap}\fp) works such that it is always executed for a handful of different type-specific memory pools. In addition, it also makes sure to allocate new memory if required.
1244
1245 \subsection {Nasal Memory Pools}
1246 A memory pool is basically a preallocated region of memory, which is dynamically resized as required. The Nasal GC works such that it manages a handful of global memory pools for all native Nasal types (strings, functions, vectors, hashes etc). At the moment, the hard coded defaults ensure that 25--50\% of additional object "slots" (memory blocks) are kept available during each execution of reap().
1247
1248 Whenever new memory is requested to create a new type (such as a vector or a string), the available memory in the corresponding pool will be checked, reachable objects will be marked, and dead objects will be removed from all pools using a mark/sweep collector, new memory blocks will be allocated if necessary. All of this happens atomically, i.e. single-threaded, in a ``stop-the-world'' fashion.
1249
1250 All Nasal memory pools are implemented using memory blocks, a memory block is implemented as a singly linked list. Each block contains a field to store its size, a pointer to the allocated memory, and another pointer to the next block.
1251
1252 \begin{lstlisting}[language=C]
1253 struct Block {
1254 int size; // size of the block
1255 char* block; // pointer to the memory region
1256 struct Block* next; // pointer to the next block
1257 };
1258 \end{lstlisting}
1259
1260 For each of the 7 Nasal data types, there is a separate storage pool used, declared as part of the "Globals" structure. As can be seen, each storage pool is addressed by its enum index (0..6):
1261 \begin{lstlisting}[language=C]
1262 enum { T_STR, T_VEC, T_HASH, T_CODE, T_FUNC, T_CCODE, T_GHOST, NUM_NASAL_TYPES };
1263 \end{lstlisting}
1264
1265 The 7 storage pools are declared in \nasalsourcefile{code.h} as part of the "Globals" structure:
1266
1267 \begin{lstlisting}[language=C]
1268 struct Globals {
1269 // Garbage collecting allocators:
1270 struct naPool pools[NUM_NASAL_TYPES];
1271 int allocCount;
1272 // Dead blocks waiting to be freed when it is safe
1273 void** deadBlocks;
1274 int deadsz;
1275 int ndead;
1276 //...
1277 };
1278 \end{lstlisting}
1279
1280 New memory blocks are allocated using \nasalapi{newBlock}\fp\ and the memory is initialized with 0:
1281
1282 \begin{lstlisting}[language=C]
1283 static void newBlock(struct naPool* p, int need)
1284 {
1285 int i;
1286 struct Block* newb;
1287 if(need < MIN_BLOCK_SIZE) need = MIN_BLOCK_SIZE;
1288 // allocate a new Block
1289 newb = naAlloc(sizeof(struct Block));
1290 // initialize the Block
1291 newb->block = naAlloc(need * p->elemsz); // number of elements * size of element
1292 newb->size = need; // set block size
1293 // memory blocks are circular linked lists:
1294 newb->next = p->blocks;
1295 p->blocks = newb;
1296 naBZero(newb->block, need * p->elemsz);
1297
1298 if(need > p->freesz - p->freetop) need = p->freesz - p->freetop;
1299 p->nfree = 0;
1300 p->free = p->free0 + p->freetop;
1301 // mark all new blocks as unreachable and add them to the pool's free list
1302 for(i=0; i < need; i++) {
1303 // initialize each new new memory blocks by setting up an naRef (the container for all Nasal references)
1304 struct naObj* o = (struct naObj*)(newb->block + i*p->elemsz);
1305 o->mark = 0;
1306 p->free[p->nfree++] = o;
1307 }
1308 p->freetop += need;
1309 }
1310 \end{lstlisting}
1311
1312 \section{Error and Exception Handling}
1313 \todo{To be written,explain setjmp, longjmp,naRuntimeError, naParseError}
1314 \subsection{Parser error handling}
1315 This information is relevant to \nasalsourcefile{lex.c}, \nasalsourcefile{parse.c}, and \nasalsourcefile{codegen.c}.
1316
1317 If an error occurs, often relevant information is lacking as there is no ``state'' of the generator, so most errors end up saying ``parse error'' and give you a line number, instead of what could be helpful information such as ``inside a foreach loop, this error occured''.
1318
1319 \subsection{VM error handling}
1320 \subsection{Exception handling via \func{call}\fp}
1321
1322 \part{Examples and Existing Work}
1323 \section{The Nasal Standard Library}
1324 \todo{document lib.c, math.c, etc.}
1325
1326 \section{Multithreading Support}
1327 \todo{document threadlib.c}
1328
1329 \section{Nasal bindings}
1330 \subsection {SQLite}
1331 \subsection {PCRE (regex)}
1332 \subsection {Cairo}
1333 \subsection {Gtk}
1334 \subsection {OpenCL}
1335
1336 %\section{Sandboxing} %(import etc)
1337
1338 \section{Embedding Nasal}
1339 \todo{Look at: nasal-bin.c, AlgoScore, FlightGear's FGNasalSys}
1340 \subsection{Basic Nasal Integration Example}
1341 \begin{enumerate}
1342 \item create a new context using \nasalapi{naNewContext}\fp
1343 \item parse the code using \nasalapi{naParseCode}\fp
1344 \item create the standard namespace using \nasalapi{naInit\_std}\fp
1345 \item add any custom symbols using \nasalapi{naAddSym}\fp\ (optional)
1346 \item add other required bindings/libraries (optional)
1347 \item use \nasalapi{naCall}\fp\ to call the code in the namespace
1348 \item do error checking using \nasalapi{naGetError}\fp
1349 \end{enumerate}
1350
1351 \begin{lstlisting}[language=C]
1352 // A Nasal extension function (prints its argument list to stdout)
1353 static naRef print(naContext c, naRef me, int argc, naRef* args)
1354 {
1355 int i;
1356 for(i=0; i<argc; i++) {
1357 naRef s = naStringValue(c, args[i]);
1358 if(naIsNil(s)) continue;
1359 fwrite(naStr_data(s), 1, naStr_len(s), stdout);
1360 }
1361 return naNil();
1362 }
1363 \end{lstlisting}
1364
1365 \subsection{Nasal Integration in FlightGear}
1366 % Also see: http://plausible.org/nasal/flightgear.html
1367 In FlightGear, Nasal is added as a \type{SGSubsystem} in the form of the \name{FGNasalSys} class in \src{\$FG\_SRC}/Scripting/NasalSys.cxx, which is mainly responsible for initializing the interpreter at the moment, as most runtime code is invoked through callbacks that are run via timers and listeners. It notably introduces FlightGear-specific extension functions, like \func{setlistener}\fp/\func{removelistener}\fp, \func{settimer}\fp, and \func{systime}\fp\ functions, and a new area of development is exposing C++ classes and alternative Nasal APIs via ghosts, like the \func{maketimer}\fp\ function does.
1368
1369 \subsubsection{Initialization}
1370 At the moment, \name{FGNasalSys} loads all the Nasal code currently. This will hopefully be changed in the future to allow a Nasal script to do all of the loading, making it a more flexible and transparent process, which is important to those who do not compile from source or understand that source but need to know how things work.
1371
1372 Initialization is a big part of running Nasal code in FlightGear and most Nasal libraries/subsystems get loaded this way. But to keep running intermittently, to provide an alternative method of loading, or to run a Nasal ``action'' script, there are three other ways to run Nasal in FlightGear: timers, listeners, and bindings.
1373 \subsubsection{Timers}
1374 Timers can be used to repetively run bits of code in a loop, somewhat like a proper subsystem in FlightGear, to delay a response to something, or to distrubute work across frames. \func{settimer}\fp\ is mainly used for this right now, and it simply registers a function to be run after a certain amount of time -- this is checked every frame, and so at maximum it can only run at frame rate. To run in a loop, the callback must re-register itself in a new timer, which is inefficient. Recently, \func{maketimer}\fp\ was introduced, which returns a Nasal ghost that is a virtual C++ timer object. This timer can be stopped, (re-)started, and told to run at a certain interval (solving the need to reregister a timer), or to just run once (like \func{settimer}\fp\ does, though \func{maketimer}\fp\ objects can be reused). These both illustrate how to constantly run code in FlightGear, and this can be very useful though being limited to the frame rate.
1375 \subsubsection{Listeners}
1376 Another solution to looping is hooking a Nasal callback to a property that is called by some subsystem updating at a potentially higher rate -- like the rate of the underlying flight dynamics model (FDM). These callbacks are called listeners, and for long-standing reasons they may not work with all properties created by C++ code, but there are some places where they are applicable. Other uses are waiting for a user input (like adjusting a preference, which may require 3D objects or even Nasal modules to be loaded or unloaded), communicating between systems, receiving direct input from C++ or other languages interfacing with FlightGear, and more. In the future, all Nasal modules other than necessary libraries might be loaded from listeners, as they provide a convient way to run Nasal code that transcends all languages in FlightGear by using the property tree.
1377 \subsubsection{Bindings/FGCommands}
1378 Bindings are the third and final way to run code. FlightGear has a core set of commands -- called fgcommands -- that interact with their caller via the property tree and can be executed from both C++ and Nasal (via the \func{fgcommand}\fp function in Nasal). These are often wrapped in ``bindings'', which are property nodes that store the name of their command and arguments to the command side-by-side. One of these commands is ``nasal'', which executes a Nasal snippet in a ``script'' node. Other commands provide access to C++ functionality, such as the flight plan. Nasal can actually register its own fgcommands, so Nasal code can even be registered to run via bindings that do not use the ``nasal'' command.
1379
1380 One of the exciting things about bindings is that they are prevalent in many areas of FlightGear. In particular, they are often used to handle user input (joystick and mouse events and ``pick'' animations on 3D objects) and can be incorporated as elements of other systems, like checklists that can be ``run'' by executing sequential bindings. These three parts of FlightGear, timers, listeners, and bindings, allow for a big diversity in how Nasal code can be executed within FlightGear. It also illustrates well what they have done with integrating Nasal into its core -- perhaps someday achieving the dream of using Nasal and C/C++ side by side.
1381
1382 \section{Nasal Maintenance}
1383 If Nasal is not maintained well and code bases around it evolve too much, then it might become a broken part of whatever it is integrated into, or even being broken by itself. When integrating Nasal into a new place, developing infrastructure to cement Nasal and the host application together will be needed, and one even might want to extend core Nasal functionality. This section aims to teach how some of these tasks can be done.
1384 \todo{to be written}
1385 \subsection{Adding a new Token}
1386 \subsection{Adding a new OP code}
1387 \subsection{Adding a new binary operator}
1388 \subsection{Adding a new loopoid}
1389 \subsection{Adding a new extension function}
1390
1391 \section{Known Bugs \& Issues}
1392 \todo{see FIXMEs, TODO in source code}
1393
1394 \section{Maintenance Examples}
1395 Some ideas (brainstorming)
1396 \begin{enumerate}
1397 \item iterating through hashes (Philosopher; done)
1398 \item serialize/unserialize functions
1399 \item json support
1400 \item native tasking primitives
1401 \item DbC: preconditions/postconditions
1402 \item protected types(via hashes) with implicit locking
1403 \item do\{\}while() construct or other loopoid (Philosopher)
1404 \item custom typing
1405 \item list comprehension
1406 \end{enumerate}
1407
1408 % only add sections here which are not just brainstorming, but for which we have actual code/examples
1409
1410 \subsection{Perl's Spaceship Operator}
1411 See \url{http://wiki.flightgear.org/How_to_add_a_new_binary_operator_to_Nasal} for the full example.
1412
1413 \subsection{Slicing Strings}
1414 Currently, Nasal only supports slicing vectors, not strings. Let's say that we want the ability to slice strings as well; how would we go about adding this? First we want to consider what stage of Nasal will be affected: parsing (\nasalsourcefile{parse.c}, \nasalsourcefile{codegen.c}) or running (\nasalsourcefile{code.c})? It's obvious that since the type of the sliced variable is a runtime property, we will only be editing \nasalsourcefile{code.c}, since anything before that has no knowledge of the types of a variable -- right? Well I thought so too, but then I looked more closely and saw that \nasalsourcefile{codegen.c} actually pushes a new vector when it sees a slice. This is an optimization that obviously does not work well with strings, and so I introduced a new opcode to push a slice of the appropriate type -- I called it \textcolor{opcode}{\sc Op\_Newslice}.
1415
1416 \subsection{Tom's String Methods}
1417
1418
1419 \section{VM Extensions}
1420 \todo{Hooray is currently playing around with a bunch of related branches}
1421 \subsection{Dumping internal data structures}
1422 \subsection{Implementing support for parser hooks}
1423 \subsection{Implementing debugging support via VM hooks and custom opcodes}
1424 \comment{breakpoint on call, breakpoint on read/write, conditional breakpoints}
1425 \subsection{Implementing instrumentation/profiling support via codegen hooks}
1426 \subsection{Implementing a bytecode optimizer via VM hooks}
1427 % Writing a simple peephole optimizer
1428 % www.stanford.edu/class/archive/cs/cs143/cs143.1112/materials/lectures/lecture14.pdf
1429 % www.d.umn.edu/~rmaclin/cs5641/Notes/L19_CodeGenerationI.pdf
1430 % inst.eecs.berkeley.edu/~cs164/sp06/lectures/lecture15cgen-6.pdf
1431 % www.complang.tuwien.ac.at/papers/maierhofer%2526ertl97.ps.gz
1432
1433 \subsection{Implementing RAII support via VM events}
1434 \subsection{Exposing GC behavior to Nasal space}
1435
1436 \subsection{Implementing a VM debugger}
1437 \begin{enumerate}
1438 \item breakpoints (via special opcodes or setjmp exceptions)
1439 \item stepping
1440 \item interactive, bash-style interface to stepping/executing code and viewing the state of the VM. Could also be useful to have a ``Nasal explorer'' as well. FGCanvas too, maybe?
1441 \end{enumerate}
1442
1443
1444
1445
1446 \section{Debugging Nasal}
1447 \comment{document usage of gdb, valgrind and debugging libs here}
1448 \todo{see various helpers in debug.c and contrib/int-nasal.c}
1449 \subsection{Dumping Tokens}
1450 \subsection{Dumping the Parse Tree}
1451 \subsection{Dumping Bytecode}
1452 \subsection{Dumping Opcode/Operand Stacks}
1453 \subsection{Dumping Stack Frames}
1454 \subsection{Dumping GC State}
1455
1456 \section{Nasal Syntax}
1457 \todo{A guide to the syntax of Nasal, loopoids, expressions, etc.}
1458
1459
1460 \end{document}
1461