1
0
forked from GitHub/gf-core

move gf.cabal and all compiler dependent files into src/compiler

This commit is contained in:
Krasimir Angelov
2022-06-18 20:42:31 +02:00
parent 96c8218564
commit a8ad145aeb
264 changed files with 71 additions and 71 deletions

View File

@@ -0,0 +1,2 @@
html:
pandoc --from=markdown+pipe_tables --to=html --output=about.html README.md

View File

@@ -0,0 +1,76 @@
<!DOCTYPE html>
<html>
<head>
<title>About the syntax editor</title>
<link rel=stylesheet type="text/css" href="../minibar/minibar.css">
<link rel=stylesheet type="text/css" href="editor.css">
<meta charset="UTF-8">
</head>
<body class="about">
# GF web-based syntax editor
John J. Camilleri
January 2013
A tool for building and manipulating abstract syntax trees in GF.
This is meant as improved replacement of the [old syntax editor][old].
[old]:http://www.grammaticalframework.org/~meza/restWiki/editor.html
## Example usage
If you want to use the tool in your own application, everything you need in the source
files `editor.html` and `editor_online.js`. Contact the [GF developer mailing list][gf-dev]
if you have any problems.
[gf-dev]:http://groups.google.com/group/gf-dev
## Available startup options
### Grammar Manager
| Options | Description | Default |
|---------------------+-------------------------------------------------------------------------+-------------------|
| `initial.grammar` | Initial grammar URL, e.g. `"http://localhost:41296/grammars/Foods.pgf"` | |
| `initial.startcat` | Initial startcat | (grammar default) |
| `initial.languages` | Initial linearisation languages, e.g. `["Eng","Swe","Mlt"]` | (all) |
### Editor
| Options | Description | Default |
|----------------------+---------------------------------------------------------------------------------+----------|
| `target` | | "editor" |
| `initial.abstr` | Initial abstract tree (as string), e.g. `"Pred (That Fish) Expensive"` | |
| `lin_action` | Function called when clicking on the language button beside each linearisation. | |
| `lin_action_tooltip` | Tooltip for the button beside each linearisation. | |
| `show_grammar_menu` | Show grammar menu? | True |
| `show_startcat_menu` | Show startcat menu? | True |
| `show_to_menu` | Show languages menu? | True |
| `show_random_button` | Show random button? | True |
| `show_import` | Show import button/panel? | True |
| `show_export` | Show export button? | True |
## Notes
- Tested with latest Chrome and Firefox (only).
## To do/feature requests
- Compatibility with grammars with dependent category types
- Clicking on tokens to select tree node
- Clipboard of trees
- Usage of printnames
- Enter string/float/int literals
- more prominence to Disamb-linearizations
- show all resulting linearization variants
- undo/redo (or back/forward) navigation
- structure fridge magnets more (eg newline before the magnet whose first letter is different)
## Known bugs
- Change startcat doesn't work when given an initial startcat
</body>
</html>

View File

@@ -0,0 +1,129 @@
<!DOCTYPE html>
<html>
<head>
<title>
About the syntax editor
</title>
<link rel=stylesheet type="text/css" href="../minibar/minibar.css"> <link rel=stylesheet type="text/css" href="editor.css"> <meta charset="UTF-8">
</head>
<body class="about">
<h1 id="gf-web-based-syntax-editor">GF web-based syntax editor</h1>
<p>John J. Camilleri<br />January 2013</p>
<p>A tool for building and manipulating abstract syntax trees in GF. This is meant as improved replacement of the <a href="http://www.grammaticalframework.org/~meza/restWiki/editor.html">old syntax editor</a>.</p>
<h2 id="example-usage">Example usage</h2>
<p>If you want to use the tool in your own application, everything you need in the source files <code>editor.html</code> and <code>editor_online.js</code>. Contact the <a href="http://groups.google.com/group/gf-dev">GF developer mailing list</a> if you have any problems.</p>
<h2 id="available-startup-options">Available startup options</h2>
<h3 id="grammar-manager">Grammar Manager</h3>
<table>
<thead>
<tr class="header">
<th align="left">Options</th>
<th align="left">Description</th>
<th align="left">Default</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td align="left"><code>initial.grammar</code></td>
<td align="left">Initial grammar URL, e.g. <code>&quot;http://localhost:41296/grammars/Foods.pgf&quot;</code></td>
<td align="left"></td>
</tr>
<tr class="even">
<td align="left"><code>initial.startcat</code></td>
<td align="left">Initial startcat</td>
<td align="left">(grammar default)</td>
</tr>
<tr class="odd">
<td align="left"><code>initial.languages</code></td>
<td align="left">Initial linearisation languages, e.g. <code>[&quot;Eng&quot;,&quot;Swe&quot;,&quot;Mlt&quot;]</code></td>
<td align="left">(all)</td>
</tr>
</tbody>
</table>
<h3 id="editor">Editor</h3>
<table>
<thead>
<tr class="header">
<th align="left">Options</th>
<th align="left">Description</th>
<th align="left">Default</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td align="left"><code>target</code></td>
<td align="left"></td>
<td align="left">&quot;editor&quot;</td>
</tr>
<tr class="even">
<td align="left"><code>initial.abstr</code></td>
<td align="left">Initial abstract tree (as string), e.g. <code>&quot;Pred (That Fish) Expensive&quot;</code></td>
<td align="left"></td>
</tr>
<tr class="odd">
<td align="left"><code>lin_action</code></td>
<td align="left">Function called when clicking on the language button beside each linearisation.</td>
<td align="left"></td>
</tr>
<tr class="even">
<td align="left"><code>lin_action_tooltip</code></td>
<td align="left">Tooltip for the button beside each linearisation.</td>
<td align="left"></td>
</tr>
<tr class="odd">
<td align="left"><code>show_grammar_menu</code></td>
<td align="left">Show grammar menu?</td>
<td align="left">True</td>
</tr>
<tr class="even">
<td align="left"><code>show_startcat_menu</code></td>
<td align="left">Show startcat menu?</td>
<td align="left">True</td>
</tr>
<tr class="odd">
<td align="left"><code>show_to_menu</code></td>
<td align="left">Show languages menu?</td>
<td align="left">True</td>
</tr>
<tr class="even">
<td align="left"><code>show_random_button</code></td>
<td align="left">Show random button?</td>
<td align="left">True</td>
</tr>
<tr class="odd">
<td align="left"><code>show_import</code></td>
<td align="left">Show import button/panel?</td>
<td align="left">True</td>
</tr>
<tr class="even">
<td align="left"><code>show_export</code></td>
<td align="left">Show export button?</td>
<td align="left">True</td>
</tr>
</tbody>
</table>
<h2 id="notes">Notes</h2>
<ul>
<li>Tested with latest Chrome and Firefox (only).</li>
</ul>
<h2 id="to-dofeature-requests">To do/feature requests</h2>
<ul>
<li>Compatibility with grammars with dependent category types</li>
<li>Clicking on tokens to select tree node</li>
<li>Clipboard of trees</li>
<li>Usage of printnames</li>
<li>Enter string/float/int literals</li>
<li>more prominence to Disamb-linearizations</li>
<li>show all resulting linearization variants</li>
<li>undo/redo (or back/forward) navigation</li>
<li>structure fridge magnets more (eg newline before the magnet whose first letter is different)</li>
</ul>
<h2 id="known-bugs">Known bugs</h2>
<ul>
<li>Change startcat doesn't work when given an initial startcat</li>
</ul>
</body>
</html>

View File

@@ -0,0 +1,366 @@
/* --- ID for a node in a tree ---------------------------------------------- */
function NodeID(x) {
this.id = new Array();
this.id.push(0);
// Initialize from input
if (x) {
var type = Object.prototype.toString.call(x);
switch (type) {
case "[object Number]": this.id = [x]; break;
case "[object String]": this.id = map(function(s){return parseInt(s)}, x.split(",")); break;
case "[object Array]" : this.id = Array.clone(x); break;
case "[object Object]": this.id = Array.clone(x.get()); break; // another NodeID
}
}
// get id
this.get = function() {
return this.id;
}
// Add child node to id
this.add = function(x) {
this.id.push(parseInt(x));
return this.id;
}
// compare with other id
this.equals = function(other) {
return JSON.stringify(this.id)==JSON.stringify(other.id);
}
// clone
this.clone = function() {
return new NodeID( this );
}
// Return NodeID as string
this.toString = function() {
return this.id.toString();
}
}
/* --- Abstract Syntax Tree (with state)------------------------------------- */
function ASTNode(data) {
for (var d in data) this[d]=data[d];
this.children = [];
if (data) for (var c in data.children) {
this.children.push( new ASTNode(data.children[c]) );
}
this.hasChildren = function(){
return this.children.length > 0;
}
// generic HOF for traversing tree
this.traverse = function(f) {
function visit(node) {
f(node);
for (var i in node.children) {
visit(node.children[i]);
}
}
visit(this);
}
}
function AST(fun, cat) {
// local helper function for building ASTNodes
var newNode = function(fun, cat) {
return new ASTNode({
"fun": fun,
"cat": cat,
"string": "", // for String literals
"deps": {}, // dependent types
"children": []
});
}
this.root = newNode(fun, cat);
this.currentID = new NodeID(); // current id in tree
this.currentNode = this.root; // current node in tree
this.getCurrentNode = function() {
return this.currentNode;
}
this.getCurrentID = function() {
return this.currentID;
}
this.setCurrentID = function(id) {
this.currentID = id; // new new NodeID(id);
this.currentNode = this.find(this.currentID);
}
this.hasParent = function() {
return this.currentID.get().length > 1;
// return !this.atRoot();
}
this.atRoot = function() {
return this.currentNode == this.root;
// return !this.hasParent();
}
this.getRoot = function() {
return this.root;
}
this.getFun = function() {
return this.currentNode.fun;
}
this.setFun = function(f) {
this.currentNode.fun = f;
}
this.getCat = function() {
return this.currentNode.cat;
}
this.setCat = function(c) {
this.currentNode.cat = c;
}
// Add a single type dependency at current node
this.addDep = function(k, type) {
// Add unassigned type variable to current
this.currentNode.deps[k] = null;
// Add actual type dep node
var node = newNode(k, type);
node.depid = k; // links to dep in parent
this._add(this.currentID, node);
return node;
}
// Add a node as child of current node
this.add = function(fun, cat) {
var node = newNode(fun,cat);
this._add(this.currentID, node);
return node;
}
// add node as child of id
this._add = function(id, node) {
var x = this.find(id);
x.children.push(node);
}
// Wrap the current node inside another node
// Doesn't check whether child_ix is within in range
this.wrap = function(typeobj, child_ix) {
var subtree = new ASTNode(this.currentNode);
this.currentNode.fun = typeobj.name;
this.currentNode.cat = typeobj.ret;
this.currentNode.children = [];
for (var i in typeobj.args) {
this.add(null, typeobj.args[i]);
}
this.currentNode.children[child_ix] = subtree;
return subtree;
}
// Wrap the current node inside another node
// Doesn't check whether child_ix is within in range
this.unwrap = function() {
var parent_id = this.currentID.clone();
parent_id.get().pop();
if (parent_id.get().length==1) {
this.root = this.currentNode;
this.currentID = new NodeID();
} else {
var gparent_id = parent_id.clone();
gparent_id.get().pop();
var gparent = this.find(gparent_id);
child_ix = parent_id.clone().get().pop();
gparent.children[child_ix] = this.currentNode;
this.currentID = parent_id;
}
}
// Determine if current node is writable (empty/no children)
this.is_writable=function() {
var cn = this.currentNode;
var blank = cn.fun == null || cn.children.length == 0;
return blank;
}
// Determine if a fun would fit in a current hole
this.fits_in_place=function(typeobj) {
var cn = this.currentNode;
var inplace = false;
if (typeobj.args.length == cn.children.length) {
var matches = 0;
for (var i in typeobj.args) {
if (typeobj.args[i] == cn.children[i].cat)
matches++;
}
inplace = matches == cn.children.length;
}
return inplace;
}
// Set entire subtree at current node
this.setSubtree = function(node) {
this._setSubtree(this.currentID, node);
}
// set tree at given id
this._setSubtree = function(id, subtree) {
var lid = Array.clone(id.get()); // clone NodeID array
var node = this.root;
if (lid.length==1) {
// Insert at root
this.currentNode = this.root = new ASTNode(subtree);
}
else {
lid.shift(); // throw away root
while (lid.length>1 && node.hasChildren()) {
node = node.children[lid.shift()];
}
this.currentNode = node.children[lid.shift()] = new ASTNode(subtree);
}
}
// Find a node in the tree from its ID
this.find = function(id) {
var lid = undefined
if (Object.prototype.toString.call(id) == "[object Object]") {
lid = Array.clone( id.get() );
} else {
alert("non-NodeID passed to AST.find()");
}
var node = this.root;
if (lid[0] == 0) lid.shift();
while (lid.length>0 && node.children.length>0) {
node = node.children[lid.shift()];
}
if (lid.length>0)
return undefined;
return node;
}
// Clear children of current node
this.removeChildren = function() {
this.currentNode.children = [];
}
// Move current ID to next hole
this.toNextHole = function() {
var id = new NodeID(this.currentID);
// loop until we're at top
while (id.get().length > 0) {
var node = this.find(id);
// first check children
for (var i in node.children) {
var child = node.children[i];
if (!child.fun) {
var newid = new NodeID(id);
newid.add(i);
this.setCurrentID(newid);
return;
}
}
// otherwise go up to parent
id.get().pop();
}
}
// Return parent of current node
this.getParent = function() {
var parent_id = this.currentID.clone();
parent_id.get().pop();
return this.find(parent_id);
}
// Move current id to child number i
this.toChild = function(i) {
if (i < this.currentNode.children.length) {
this.currentID.add(i);
this.currentNode = this.currentNode.children[i];
}
}
// generic HOF for traversing tree
// this.traverse = function(f) {
// this.root.traverse(f);
// }
this.traverse = function(f) {
function visit(id, node) {
f(node);
for (var i in node.children) {
var newid = new NodeID(id);
newid.add(parseInt(i));
visit(newid, node.children[i]);
}
}
visit(new NodeID(), this.root);
}
// Return tree as string
this.toString = function() {
var s = "";
function visit(node) {
if (node.cat == "String")
s += '"' + ((node.string) ? node.string : "") + '"';
else
s += node.fun ? node.fun : "?" ;
if (!node.hasChildren())
// if (node.children.length == 0)
return;
for (var i in node.children) {
s += " (";
visit(node.children[i]);
s += ")";
}
}
visit(this.root);
return s;
}
}
// Parse type signature into a JSON object
// (This probably needs a better home)
AST.parse_type_signature = function(str) {
var obj = {
signature: str,
type: undefined,
name: undefined,
deps: [],
args: [],
ret: undefined
};
var ix = str.indexOf(":");
// judgement type
var bits = str.substr(0, ix).trim().split(" ");
obj.type = bits[0];
// name (possibly with constructors)
obj.name = bits.slice(1).join(" ");
// function args (possibly with type dependency)
var regex_dep = new RegExp(/\(\s*(.+?)\s*:\s*(.+?)\s*\)/);
var bits = map(function(s){return s.trim()}, str.substr(ix+1).split("->"));
for (var i=0 ; i<bits.length-1; i++) {
var bit = bits[i];
var m = regex_dep.exec(bit);
if (m == null) {
obj.args.push(bit);
} else {
// We have a type dependency
obj.deps.push({ "id": m[1], "type": m[2] });
}
}
//return type
obj.ret = bits[bits.length-1];
return obj;
}

View File

@@ -0,0 +1,140 @@
body.syntax-editor {
background: #ccc url("../minibar/brushed-metal.png");
}
.hidden
{
display:none;
}
.editor select#to_menu
{
height: 10em;
position: absolute;
min-width: 5em;
}
#import
{
position: absolute;
display: inline-block;
padding: 0.3em;
background: #EEE;
border: 1px solid #999;
font-size: 0.95em;
box-shadow: 2px 2px 4px rgba(0, 0, 0, 0.3);
}
#import.hidden
{
display: none;
}
#import input[type=text]
{
width: 20em;
font-family: monospace;
padding: 0.2em;
}
#tree, #tree_str
{
white-space:pre-wrap;
font-family: monospace;
background: rgba(238, 238, 238, 0.6);
padding:0.5em;
margin:0.5em 0;
}
#tree .node
{
margin: 0.5em 0 0.5em 0.75em;
border-left: 1px dashed #BBB;
padding-left: 1.25em;
}
#tree .node.first
{
margin-left: 0;
border-left: none;
}
#tree .node a
{
cursor: pointer;
}
#tree .node a:hover
{
text-decoration: underline;
}
#tree .node a.current
{
font-weight: bold;
}
#tree_str
{
font-size:0.85em;
color:#666;
}
#refinements
{
/* display: inline-block; */
/* margin-left: 0.5em; */
margin-top: 0.3em;
border: 3px solid #e0e0e0;
padding: 5px;
}
#linearisations
{
/* background: rgba(170, 170, 170, 0.5); */
/* padding:0.5em; */
margin:0.5em 0;
}
#linearisations div
{
padding:0.2em;
}
#linearisations .lang
{
display: inline-block;
margin-right: 0.5em;
width: 3em;
font-weight: bold;
text-align: center;
}
#linearisations .lin
{
}
.refinement
{
margin: 0.1em;
display: inline-block;
cursor: pointer;
border: 1px solid;
padding: 0.2em;
font: 0.9em sans-serif;
background: white;
box-shadow: 2px 2px 4px rgba(0, 0, 0, 0.3);
}
.refinement.disabled
{
opacity: 0.5;
}
div#debug
{
font: 10px monospace;
white-space: pre-wrap;
color: #333;
margin: 1em 0;
border: 1px dashed #999;
padding: 1em;
}
/* From http://www.grammaticalframework.org/css/style.css */
.about table { border-collapse: collapse; }
.about th,
.about td { border: 1px solid #333; padding:0 5px; }
.about td { background: white; }
.about th { background: #9df; }

View File

@@ -0,0 +1,46 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="author" href="http://www.grammaticalframework.org/~john/" title="John J. Camilleri">
<title>Syntax Editor</title>
<link rel="stylesheet" type="text/css" href="../minibar/minibar.css" />
<link rel="stylesheet" type="text/css" href="editor.css" />
</head>
<body class="syntax-editor">
<h2>Syntax Editor</h2>
<div id="minibar"></div>
<div id="editor"></div>
<noscript>This page doesn't work unless JavaScript is enabled.</noscript>
<hr />
<small class="modtime">
John J. Camilleri, December 2012 </br>
[ <a href="about.html">About syntax editor</a>
| <a href="../minibar/minibar.html">Minibar</a> ]
</small>
<div id="debug" class="hidden"></div>
<!-- Common -->
<script type="text/javascript" src="../js/grammar_manager.js"></script>
<script type="text/javascript" src="../js/support.js"></script>
<script type="text/JavaScript" src="../js/localstorage.js"></script>
<script type="text/javascript" src="../js/pgf_online.js"></script>
<script type="text/JavaScript" src="../js/langcode.js"></script>
<!-- Editor -->
<script type="text/javascript" src="ast.js"></script>
<script type="text/javascript" src="editor_menu.js"></script>
<script type="text/javascript" src="editor.js"></script>
<!-- Minibar -->
<script type="text/JavaScript" src="../minibar/minibar.js"></script>
<script type="text/JavaScript" src="../minibar/minibar_input.js"></script>
<script type="text/JavaScript" src="../minibar/minibar_translations.js"></script>
<script type="text/JavaScript" src="../minibar/minibar_support.js"></script>
<!-- Get us rolling! -->
<script type="text/javascript" src="editor_online.js"></script>
</body>
</html>

View File

@@ -0,0 +1,588 @@
/* --- Main Editor object --------------------------------------------------- */
function Editor(gm,opts) {
var t = this;
/* --- Configuration ---------------------------------------------------- */
// default values for options:
this.options={
target: "editor",
initial: {
grammar: null,
startcat: null,
languages: null,
abstr: null,
node_id: null
},
show: {
grammar_menu: true,
startcat_menu: true,
to_menu: true,
random_button: true
}
}
// Apply supplied options
if(opts) for(var o in opts) this.options[o]=opts[o];
/* --- Creating UI components ------------------------------------------- */
this.container = document.getElementById(this.options.target);
this.container.classList.add("editor");
this.ui = {
menubar: div_class("menu"),
tree: div_id("tree"),
tree_str: div_id("tree_str"),
actionbar: div_id("actions"),
clear_button: button("Clear", function(){
t.clear_node();
}),
wrap_button: button("Wrap…", function(){
t.wrap_candidates();
}),
unwrap_button: button("Unwrap", function(){
t.unwrap();
}),
refinements: div_id("refinements"),
lin: div_id("linearisations")
};
this.ui.clear_button.title = "Clear current node and all its children";
this.ui.wrap_button.title = "Wrap the current node with a new function";
this.ui.unwrap_button.title = "Replace parent of current node with current node (if possible)";
appendChildren(this.container, [
t.ui.menubar,
t.ui.tree,
t.ui.tree_str,
t.ui.actionbar,
t.ui.lin
]);
appendChildren(this.ui.actionbar, [
t.ui.clear_button,
t.ui.wrap_button,
t.ui.unwrap_button,
t.ui.refinements
]);
/* --- Client state initialisation -------------------------------------- */
this.gm = gm;
this.server = gm.server;
this.ast = null;
this.clear_on_change_startcat = true; // temp. false when wrapping
/* --- Register Grammar Manager hooks ----------------------------------- */
this.hook_change_grammar = function(grammar){
debug("Editor: change grammar");
var args = {
format: "json"
};
var cont = function(data){
t.process_grammar_constructors(data);
t.start_fresh();
};
t.server.browse(args, cont);
};
this.hook_change_startcat = function(startcat){
debug("Editor: change startcat");
t.startcat = startcat;
if (t.clear_on_change_startcat)
t.start_fresh();
};
this.hook_change_languages = function(languages){
debug("Editor: change languages");
t.update_linearisation();
};
this.gm.register_action("change_grammar",this.hook_change_grammar);
this.gm.register_action("change_startcat",this.hook_change_startcat);
this.gm.register_action("change_languages",this.hook_change_languages);
/* --- Main program, this gets things going ----------------------------- */
this.menu = new EditorMenu(this, this.options);
/* --- Other basic stuff ------------------------------------------------ */
this.shutdown = function() {
t.gm.unregister_action("change_grammar",t.hook_change_grammar);
t.gm.unregister_action("change_startcat",t.hook_change_startcat);
t.gm.unregister_action("change_languages",t.hook_change_languages);
clear(t.container);
t.container.classList.remove("editor");
}
this.hide = function() {
t.container.style.display="none";
}
this.show = function() {
t.container.style.display="block";
}
}
/* --- Pre-processed grammar information ------------------------------------ */
Editor.prototype.process_grammar_constructors=function(data) {
var t = this;
t.grammar_constructors=data;
for (var fun in t.grammar_constructors.funs) {
var def = t.grammar_constructors.funs[fun].def;
var typeobj = AST.parse_type_signature(def);
t.grammar_constructors.funs[fun] = typeobj;
}
}
// Look up information for a category
Editor.prototype.lookup_cat = function(cat) {
var t = this;
return t.grammar_constructors.cats[cat];
}
// Look up information for a function
Editor.prototype.lookup_fun = function(fun) {
var t = this;
return t.grammar_constructors.funs[fun];
}
/* --- API for getting and setting state ------------------------------------ */
Editor.prototype.get_ast=function() {
return this.ast.toString();
}
Editor.prototype.get_startcat=function() {
return this.gm.startcat;
}
// Called from Minibar, for example
Editor.prototype.initialize_from=function(opts) {
var t = this;
if (opts.abstr) {
t.ast = new AST(null, t.get_startcat());
t.import_ast(opts.abstr);
}
}
// Called after changing grammar or startcat
Editor.prototype.start_fresh=function () {
var t = this;
t.ast = new AST(null, t.get_startcat());
if (t.options.initial.abstr) {
t.import_ast(t.options.initial.abstr);
t.options.initial.abstr = null; // don't use again
}
t.update_current_node();
clear(t.ui.lin);
}
/* --- Functions for handling tree manipulation ----------------------------- */
// Add refinement to UI, returning object
Editor.prototype.add_refinement=function(fun,opts) {
var t = this;
options = {
label: fun,
disable_destructive: false
};
if (opts) for (var o in opts) options[o] = opts[o];
var typeobj = t.lookup_fun(fun);
// hide refinement if identical to current fun?
var opt = span_class("refinement", text(options.label));
opt.title = typeobj.signature;
// If refinement would be destructive, disable it
if (options.disable_destructive) {
var blank = t.ast.is_writable();
var inplace = t.ast.fits_in_place(typeobj);
if (!blank && !inplace) {
opt.classList.add("disabled");
}
}
t.ui.refinements.appendChild(opt);
return opt;
}
// Add a literal refinement to UI, e.g. String
Editor.prototype.add_literal_refinement=function() {
var t = this;
t.ui.refinements.innerHTML = "Enter string: ";
var nde = t.ast.getCurrentNode();
var val = (nde.string) ? nde.string : "";
var input = node("input",{
type:"text",
value: val
},[]);
// TODO: Perhaps we should have an update button instead
input.onkeyup = function() {
nde.string = input.value;
t.redraw_tree();
t.update_linearisation();
}
t.ui.refinements.appendChild(input);
}
// Show refinements for given cat (usually that of current node)
Editor.prototype.get_refinements=function(cat) {
var t = this;
t.ui.refinements.innerHTML = "…";
if (cat == undefined) cat = t.ast.getCat();
// Special case when cat is "String"
if (cat == "String") {
t.add_literal_refinement();
return;
}
var args = {
id: cat,
format: "json"
};
var cont = function(data){
clear(t.ui.refinements);
// t.ui.refinements.innerHTML = "Refinements: ";
function addClickHandler(fun) {
return function() {
t.select_refinement.apply(t,[fun]);
}
}
for (var pi in data.producers) {
var fun = data.producers[pi];
var ref = t.add_refinement(fun, {
disable_destructive: true
});
ref.onclick = addClickHandler(fun);
}
};
var err = function(data){
clear(t.ui.refinements);
alert("Error");
};
t.server.browse(args, cont, err);
}
// Select refinement now by default replaces "in-place"
// Case 1: current node is blank/no kids
// Case 2: kids have all same types, perform an in-place replacement
// Case 3: kids have diff types/number, prevent replacement (must clear first)
Editor.prototype.select_refinement=function(fun) {
var t = this;
// Check if current node is blank or childless (case 1)
var blank = t.ast.is_writable();
// Check if we can replace in-place (case 2)
var typeobj = t.lookup_fun(fun);
var inplace = !blank && t.ast.fits_in_place(typeobj);
if (!blank && !inplace) {
alert("Use 'Clear' first if you want to replace the subtree.");
return;
}
t.ast.setFun(fun);
if (blank) {
t.ast.removeChildren();
// Add dependent type placeholders
if (typeobj.deps.length > 0) {
alert("the syntax editor current doesn't support dependent types");
// for (var i in typeobj.deps) {
// t.ast.addDep(typeobj.deps[i].id, typeobj.deps[i].type);
// }
}
// Add function argument placeholders
if (typeobj.args.length > 0) {
for (var i in typeobj.args) {
t.ast.add(null, typeobj.args[i]);
}
}
}
// Update ui
t.redraw_tree();
t.update_linearisation();
// Select next hole & get its refinements
t.ast.toNextHole();
t.update_current_node();
}
Editor.prototype.update_current_node=function(newID) {
with(this) {
if (newID)
ast.setCurrentID(newID);
redraw_tree();
get_refinements();
}
}
// Clear current node and all its children
Editor.prototype.clear_node = function() {
var t = this;
t.ast.removeChildren();
t.ast.setFun(null);
t.redraw_tree();
t.get_refinements();
}
// Show wrap candidates
Editor.prototype.wrap_candidates = function() {
var t = this;
// we need to end with this
var cat = t.ast.getCat();
var refinements = [];
for (var i in t.grammar_constructors.funs) {
var obj = t.grammar_constructors.funs[i];
if (elem(cat, obj.args)) {
// if no parent, then cat can be anything
// as long as the current tree fits somewhere
if (!t.ast.hasParent() || obj.ret==cat) {
refinements.push(obj);
}
}
}
if (refinements.length == 0) {
alert("No functions exist which can wrap the selected node.");
return;
}
// Display wrap refinements
function addClickHandler(fun, child_ix) {
return function() {
t.wrap.apply(t,[fun, child_ix]);
}
}
t.ui.refinements.innerHTML = "Wrap with: ";
for (var i in refinements) {
var typeobj = refinements[i];
var fun = typeobj.name;
// Find valid child ids
var child_ixs = [];
for (var a in typeobj.args) {
if (typeobj.args[a] == cat) {
child_ixs.push(a);
}
}
// if (child_ixs.length < 2) {
// var ref = t.add_refinement(fun);
// ref.onclick = addClickHandler(typeobj.name, a);
// } else {
// Show a refinement for each potential child position
for (var c in child_ixs) {
var id = child_ixs[c];
var label = fun;
for (var a in typeobj.args) {
if (a == id)
if (t.ast.currentNode.hasChildren())
label += " ("+t.ast.currentNode.fun+" …)";
else
label += " "+t.ast.currentNode.fun;
else
label += " ?";
}
var ref = t.add_refinement(typeobj.name, {label: label});
ref.onclick = addClickHandler(typeobj.name, id);
}
// }
}
}
// Wrap the current node inside another function
Editor.prototype.wrap = function(fun, child_ix) {
var t = this;
var typeobj = t.grammar_constructors.funs[fun];
// if we are at root node, potentially change startcat
if (t.ast.atRoot() && t.get_startcat() != typeobj.ret) {
var old_val = t.clear_on_change_startcat;
t.clear_on_change_startcat = false;
t.gm.change_startcat(typeobj.ret);
t.clear_on_change_startcat = old_val;
}
// do actual replacement
t.ast.wrap(typeobj, child_ix);
// refresh stuff
t.redraw_tree();
t.update_linearisation();
t.ast.toNextHole();
t.update_current_node();
}
// Unwrap a node by deleting a fun with same input/output category
Editor.prototype.unwrap = function() {
var t = this;
var fun = t.ast.getFun();
var typeobj = t.grammar_constructors.funs[fun];
// Cannot unwrap when at root
if (t.ast.atRoot()) {
alert("It is not possible to unwrap the top node");
return;
}
var child = t.ast.getCurrentNode();
var parent = t.ast.getParent();
// TODO: We can also unwrap when at level one and cats don't match
// Check if unwrap is possible
if (parent.children.length==1 &&
(parent.cat==child.cat || parent==t.ast.getRoot())
) {
// do actual unwrap
t.ast.unwrap();
// if root node changed, potentially change startcat
var rootcat = t.ast.getRoot().cat;
if (rootcat != t.get_startcat()) {
var old_val = t.clear_on_change_startcat;
t.clear_on_change_startcat = false;
t.gm.change_startcat(rootcat);
t.clear_on_change_startcat = old_val;
}
// refresh stuff
t.redraw_tree();
t.update_linearisation();
// t.ast.toNextHole();
// t.update_current_node();
} else {
alert("Cannot unwrap this node");
}
}
// Generate random subtree from current node
Editor.prototype.generate_random = function() {
var t = this;
t.ast.removeChildren();
var args = {
cat: t.ast.getCat(),
limit: 1
};
if (!args.cat) {
alert("Missing category at current node");
return;
}
var cont = function(data){
var tree = data[0].tree;
t.import_ast(tree);
};
var err = function(data){
alert("Error");
};
t.server.get_random(args, cont, err);
}
// Redraw tree
Editor.prototype.redraw_tree=function() {
var t = this;
var elem = node; // function from support.js
function visit(container, id, node) {
var container2 = empty_class("div", "node");
if (id.get().length == 1)
container2.classList.add("first");
// Special case for String literal
if (node.cat == "String") {
var label =
'"' + ((node.string) ? node.string : "") + '"' +
" : String";
} else {
var label =
((node.fun) ? node.fun : "?") + " : " +
((node.cat) ? node.cat : "?");
}
var current = id.equals(t.ast.getCurrentID());
var element = elem("a", {class:(current?"current":"")}, [text(label)]);
element.onclick = function() {
t.update_current_node(id);
}
container2.appendChild( element );
for (var i in node.children) {
var newid = new NodeID(id);
newid.add(parseInt(i));
visit(container2, newid, node.children[i]);
}
container.appendChild(container2);
}
with(this) {
clear(ui.tree);
ui.tree_str.innerText = ast.toString();
visit(ui.tree, new NodeID(), ast.root);
}
}
// Get and display linearisations for AST
Editor.prototype.update_linearisation=function(){
var t = this;
// langpart("FoodsEng","Foods") == "Eng"
function langpart(conc,abs) {
return hasPrefix(conc,abs) ? conc.substr(abs.length) : conc;
}
function row(lang, lin) {
var langname = langpart(lang, t.gm.grammar.name);
var btn = button(langname, function(){
bind(t.options.lin_action,t)(lin,lang);
});
if (t.options.lin_action_tooltip) {
btn.title = t.options.lin_action_tooltip;
}
var c1 = th(btn);
var c2 = td(text(lin));
var row = tr([c1,c2]);
return row;
}
var args = {
tree: t.ast.toString()
};
t.server.linearize(args, function(data){
clear(t.ui.lin);
var tbody=empty("tbody");
for (var i in data) {
var lang = data[i].to;
if (t.gm.languages.length < 1 || elem(lang, t.gm.languages)) {
tbody.appendChild(row(lang, data[i].text))
}
}
t.ui.lin.appendChild(wrap("table",tbody));
});
}
// Import AST from string representation, setting at current node
Editor.prototype.import_ast = function(abstr) {
var t = this;
var args = {
tree: abstr
};
var cont = function(tree){
// Build tree of just fun, then populate with cats
t.ast.setSubtree(tree);
/// TODO: traverse only subtree, not everything!
t.ast.traverse(function(node){
if (!node.fun) return;
var typeobj = t.lookup_fun(node.fun);
node.cat = typeobj.ret;
});
t.redraw_tree();
t.update_linearisation();
};
var err = function(tree){
alert("Invalid abstract syntax tree");
};
t.server.pgf_call("abstrjson", args, cont, err);
}

View File

@@ -0,0 +1,197 @@
/* --- Editor Menu object --------------------------------------------------- */
function EditorMenu(editor,opts) {
var t = this;
/* --- Configuration ---------------------------------------------------- */
// default values for options:
this.options={
target: "editor",
show_grammar_menu: true,
show_startcat_menu: true,
show_to_menu: true,
show_random_button: true,
show_import: true,
show_debug: false,
}
// Apply supplied options
if(opts) for(var o in opts) this.options[o]=opts[o];
/* --- Creating UI components ------------------------------------------- */
this.container = editor.ui.menubar;
this.ui = {
grammar_menu: empty_id("select","grammar_menu"),
startcat_menu: empty("select"),
to_toggle: button("Languages…", function(){
toggleHidden(t.ui.to_menu);
}),
to_menu: node("select",{
id: "to_menu",
multiple: "multiple",
class: "hidden"
}),
random_button: button("Random", function(){
t.editor.generate_random();
}),
import: {
toggle: button("Import…", function(){
toggleHidden(t.ui.import.panel);
}),
panel: node("div",{
id: "import",
class: "hidden"
}),
input: node("input",{type:"text"},[]),
button: button("Import", function(){
t.editor.import_ast(t.ui.import.input.value);
toggleHidden(t.ui.import.panel);
})
},
debug_toggle: button("⚙", function(){
toggleHidden(element("debug"));
})
};
this.ui.to_toggle.title = "Select languages to linearise to (use Ctrl/Shift to select multiple)";
this.ui.random_button.title = "Insert a randomly generated tree at the current node";
this.ui.import.toggle.title = "Import an abstract syntax tree from a string (replaces current tree)";
this.ui.debug_toggle.title = "Toggle the debug console";
if (t.options.show_grammar_menu) {
appendChildren(t.container, [text(" Grammar: "), t.ui.grammar_menu]);
t.ui.grammar_menu.onchange = function(){
var grammar_url = t.ui.grammar_menu.value;
t.gm.change_grammar(grammar_url);
}
}
if (t.options.show_startcat_menu) {
appendChildren(t.container, [text(" Start Category: "), t.ui.startcat_menu]);
t.ui.startcat_menu.onchange = function(){
var startcat = t.ui.startcat_menu.value;
t.gm.change_startcat(startcat);
}
}
if (t.options.show_to_menu) {
appendChildren(t.container, [text(" To: "), t.ui.to_toggle, t.ui.to_menu]);
t.ui.to_menu.onchange = function(){
var languages = multiMenuSelections(t.ui.to_menu)
t.gm.change_languages(languages);
}
}
if (t.options.show_random_button) {
appendChildren(t.container, [t.ui.random_button]);
}
if (t.options.show_import) {
appendChildren(t.container, [
t.ui.import.toggle,
t.ui.import.panel
]);
appendChildren(t.ui.import.panel, [
text("Import AST: "),
t.ui.import.input,
t.ui.import.button
]);
}
if (t.options.show_debug) {
appendChildren(t.container, [t.ui.debug_toggle]);
}
/* --- Client state initialisation -------------------------------------- */
this.editor = editor;
this.gm = editor.gm;
this.server = editor.server;
/* --- Register Grammar Manager hooks ----------------------------------- */
this.gm.register_action("onload", bind(this.hook_onload, this));
this.gm.register_action("change_grammar", bind(this.hook_change_grammar, this));
this.gm.register_action("change_startcat", bind(this.hook_change_startcat, this));
}
/* --- Grammar menu --------------------------------------------------------- */
// show the grammar list
EditorMenu.prototype.hook_onload=function(dir,grammar_names,dir_count) {
debug("EditorMenu: onload");
var t=this;
var first_time=t.ui.grammar_menu.options.length == 0;
if(first_time) {
t.grammars=[];
t.grammar_dirs=[];
}
t.grammar_dirs.push(dir);
t.grammars=t.grammars.concat(grammar_names.map(function(g){return dir+g}))
function glabel(g) {
return hasPrefix(dir,"/tmp/gfse.") ? "gfse: "+g : g
}
function opt(g) { return option(glabel(g),dir+g); }
appendChildren(t.ui.grammar_menu, map(opt, grammar_names));
function pick_first_grammar() {
if(t.timeout) clearTimeout(t.timeout),t.timeout=null;
var grammar0=t.gm.options.initial.grammar;
if(!grammar0) grammar0=t.grammars[0];
t.ui.grammar_menu.value=grammar0;
// t.change_grammar();
}
// Wait at most 1.5s before showing the grammar menu.
if(first_time) t.timeout=setTimeout(pick_first_grammar,1500);
if(t.grammar_dirs.length>=dir_count) pick_first_grammar();
}
// Copied from minibar.js
EditorMenu.prototype.hook_change_grammar=function(grammar) {
debug("EditorMenu: change grammar");
var t=this;
t.update_startcat_menu(grammar);
t.update_language_menu(t.ui.to_menu, grammar);
}
/* --- Start category menu -------------------------------------------------- */
// Called from hook_change_grammar
EditorMenu.prototype.update_startcat_menu=function(grammar) {
var t=this;
var menu=this.ui.startcat_menu;
menu.innerHTML="";
var cats=grammar.categories;
for(var cat in cats) menu.appendChild(option(cats[cat],cats[cat]))
var startcat0 = t.gm.options.initial.startcat;
if (elem(startcat0, cats))
menu.value = startcat0;
else
menu.value = grammar.startcat;
}
// If startcat changed externally, update menu
EditorMenu.prototype.hook_change_startcat=function(startcat) {
debug("EditorMenu: change startcat");
var t=this;
var menu=this.ui.startcat_menu;
menu.value = startcat;
}
/* --- Langugage (to) menu -------------------------------------------------- */
// Called from hook_change_grammar
EditorMenu.prototype.update_language_menu=function(menu,grammar) {
var t = this;
function langpart(conc,abs) { // langpart("FoodsEng","Foods") == "Eng"
return hasPrefix(conc,abs) ? conc.substr(abs.length) : conc;
}
// Replace the options in the menu with the languages in the grammar
var langs=grammar.languages;
menu.innerHTML="";
for(var i=0; i<langs.length; i++) {
var ln=langs[i].name;
if(!hasPrefix(ln,"Disamb")) {
var lp=langpart(ln,grammar.name);
var opt=option(lp,ln);
if (elem(ln, t.gm.languages)) {
opt.selected=true;
}
menu.appendChild(opt);
}
}
}

View File

@@ -0,0 +1,65 @@
var server_options = {
// grammars_url: "http://www.grammaticalframework.org/grammars/",
// grammars_url: "http://localhost:41296/grammars/",
}
var editor_options = {
target: "editor",
initial: {
// abstr: "PropOpenDate (SuperlPlace TheMostExpensive School) Tomorrow"
},
show: {
grammar_menu: true,
startcat_menu: true,
to_menu: true,
random_button: true
}
}
var gm_options = {
initial: {
// grammar: "http://localhost:41296/grammars/Smart.pgf",
// startcat: "Command",
// languages: ["Eng","Swe"]
}
}
if(window.Minibar) // Minibar loaded?
editor_options.lin_action_tooltip="Load sentence in Minibar";
editor_options.lin_action=function(s,langFrom) {
var editor=this;
var minibar_options = {
target: "minibar",
show_abstract: true,
show_trees: true,
show_grouped_translations: false,
show_brackets: true,
word_replacements: true,
initial_grammar: editor.menu.ui.grammar_menu.value, // hmm
initial: {
from: langFrom,
input: s.split(" "), // is it that easy?
startcat: editor.menu.ui.startcat_menu.value // hmm
},
initial_toLangs: multiMenuSelections(editor.menu.ui.to_menu), // hmm
// get us back to the editor!
abstract_action: function(tree) {
var opts = {
abstr: tree
}
editor.initialize_from(opts);
editor.minibar.hide();
editor.show();
}
}
editor.hide();
editor.minibar=new Minibar(server,minibar_options);
//editor.minibar.editor = editor; // :S
editor.minibar.show();
}
if(/^\?\/tmp\//.test(location.search)) {
var args=decodeURIComponent(location.search.substr(1)).split(" ")
if(args[0]) server_options.grammars_url=args[0];
}
var server = pgf_online(server_options);
var gm = new GrammarManager(server, gm_options);
var editor = new Editor(gm, editor_options);