Creating a basic interpreter for a simple programming language and incorporating it into a web page using JavaScript is a challenging but rewarding task. I’ll guide you through the process of setting up a basic web page and implementing a simple interpreter for a hypothetical programming language called "WebLang". This language will feature basic arithmetic operations and variable assignments.
Step 1: Set Up the Web Page
We'll start with a basic HTML structure and some JavaScript to interpret the language.
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>WebLang Interpreter</title>
</head>
<body>
<h1>WebLang Interpreter</h1>
<textarea id="code" rows="10" cols="50" placeholder="Write your WebLang code here..."></textarea>
<br>
<button onclick="run()">Run</button>
<pre id="output"></pre>
<script>
function run() {
const code = document.getElementById('code').value;
const outputElement = document.getElementById('output');
const interpreter = new WebLangInterpreter();
try {
const result = interpreter.run(code);
outputElement.textContent = result;
} catch (error) {
outputElement.textContent = 'Error: ' + error.message;
}
}
class WebLangInterpreter {
constructor() {
this.variables = {};
}
run(code) {
const lines = code.split('\\n');
let output = '';
for (let line of lines) {
line = line.trim();
if (!line) continue; // Skip empty lines
const tokens = line.split(' ');
if (tokens[0] === 'print') {
const expr = tokens.slice(1).join(' ');
const value = this.evaluate(expr);
output += value + '\\n';
} else if (tokens.includes('=')) {
this.handleAssignment(tokens);
} else {
throw new Error('Unknown command: ' + line);
}
}
return output;
}
handleAssignment(tokens) {
const varName = tokens[0];
const expr = tokens.slice(2).join(' '); // Skip `varName =`
const value = this.evaluate(expr);
this.variables[varName] = value;
}
evaluate(expr) {
// Simple arithmetic evaluation (only +, -, and numerical values for demo purposes)
const sanitizedExpr = expr.replace(/[a-zA-Z_][a-zA-Z0-9_]*/g, match => {
if (this.variables.hasOwnProperty(match)) {
return this.variables[match];
} else {
throw new Error('Undefined variable: ' + match);
}
});
try {
// Use Function constructor for safe evaluation
return Function('"use strict"; return (' + sanitizedExpr + ')')();
} catch {
throw new Error('Invalid expression: ' + expr);
}
}
}
</script>
</body>
</html>
Step 2: Understanding the Code
HTML/CSS: We use a simple HTML form with a <textarea> for entering code and a <button> to execute it. The <pre> tag displays the output.
JavaScript:
A class WebLangInterpreter is used to process the code. It splits the input into lines and processes each line.
Simple syntax:
Assignment: x = 5 + 3
Print: print x
The interpreter evaluates expressions using basic arithmetic operations and handles variable assignment.
We replace variable names with their values before evaluating expressions using JavaScript's Function constructor for an isolated scope.
Step 3: Limitations
This example covers a very basic interpreter for demonstration purposes. The interpreter handles:
Variable assignments.
Simple arithmetic operations.
print statements.
Many real-world features such as error handling, complex expressions, and additional operators would require a more comprehensive implementation involving parsing techniques like Abstract Syntax Tree (AST) generation.
You can extend this to add more features like loops, conditionals, and more complex expressions. Be careful when using eval or Function for expression evaluation due to potential security risks, and always sanitize inputs in a real environment.
User
ok give example code
Assistant
Certainly! Let's use the simple language "WebLang" from the interpreter above. Here's an example of what the WebLang code might look like and what it can do. We'll write some simple programs that utilize variable assignment and arithmetic operations.
Example WebLang Code
plaintext
# This is WebLang pseudo code, it won't be executed in the real environment
x = 10
y = 20
z = x + y
print z
a = 5
b = a + x
print b
c = b - y
print c
Explanation
Variable Assignment:
x = 10, y = 20
Assigns the value 10 to x and 20 to y.
Arithmetic:
z = x + y: Computes the sum of x and y and assigns it to z.
Output:
print z: Output the value of z, which should be 30.
More Calculations:
a = 5: Assigns 5 to a.
b = a + x: Computes the sum 5 + 10 and assigns it to b.
The program outputs b with print b, which is 15.
Subtraction:
c = b - y: Subtracts y from b (i.e., 15 - 20) and assigns the result to c.
print c: Outputs the result, which is -5.
Running the Code
You would paste this code into the <textarea> element of your web page, and clicking "Run" will display the results within the <pre> element styled as the output area.
Extending the Language
This example is quite basic. If you want to extend the language further, here are some ideas:
Implement more arithmetic operations like multiplication and division.
Allow for comments (e.g., lines starting with #) or more complex expression parsing.
Add support for conditional expressions and loops.
Implement functions for reuse of code logic.
You would need to change the interpreter logic to handle these expanded language features, involving more sophisticated parsing and interpretation techniques.
User
ok write a fully functioning interpreter
Assistant
Creating a fully functioning interpreter for a more sophisticated language like "WebLang" involves designing a more complex structure to handle parsing, execution, and error handling. Below, I’ll expand on the previous example to build a more advanced interpreter. This example will support:
Variable assignments.
Arithmetic operations (+, -, *, /).
Print statements.
Comments.
Basic error handling.
This implementation remains relatively simple but adds necessary sophistication for more real-world use.
Code
Here's the HTML and JavaScript code for this advanced interpreter:
html
User
its for basic web dev name (title element) title(h1) text(p) list(you understand)
Assistant
Sure, let's modify the basic interpreter to support a specialized language tailored for simple web development tasks. This language will allow users to create a structured HTML document with titles, paragraphs, and lists. We'll call this language "WebDocLang".
Language Features
Title: Set a title for the HTML document.
Heading: Add an <h1> header.
Paragraph: Add a <p> paragraph.
List: Add an ordered or unordered list.
Interpreter Example
Here’s how we can implement it:
html
User
incorporate some css
Assistant
Certainly! Let's incorporate some basic CSS styling into the "WebDocLang" interpreter. We'll add a command to include CSS styles for various elements such as the title, heading, paragraphs, and lists. This will demonstrate how to generate styled HTML using our custom language.
Features
Style Command: A command to specify CSS rules applied to elements like headings, paragraphs, and lists.
Updated Code
Here’s how you can include styling capabilities:
html
User
ok make the styling eg. TEXT bla bla COLOR Blue
Assistant
To suit your requirements, let's modify the syntax for the styling in the WebDocLang interpreter to make it more natural language-like, using uppercase commands like TEXT, COLOR, etc. We'll interpret these commands to generate the appropriate HTML and CSS.
Here's how the code can be updated to support these new style commands:
Updated Code with Enhanced Styling Syntax
html
User
there is no style the style is in the element eg text
Assistant
Let's adjust the WebDocLang syntax such that the styles are included directly within the element commands themselves. Instead of having a separate STYLE command, the styling can be embedded within each element statement.
Updated Interpreter with In-Line Style Commands
This version allows you to specify style attributes directly with each HTML element command, enhancing readability and usability:
html
User
ok you are getting it just one more
Assistant
Great! Let's refine the WebDocLang interpreter to make it even more intuitive and comprehensive based on the feedback. We'll focus on ensuring the syntax is natural and easy to follow while allowing styling of elements directly within the commands.
Here's an enhanced version:
html
User
add js function like button clicks
Assistant
To add JavaScript functionality such as handling button clicks within our custom scripting language WebDocLang, we'll need to incorporate a way to define buttons and specify functions to be executed when those buttons are clicked.
Below, I'll show you how to extend the interpreter to support defining buttons with click event handlers.
Updated Code with Button Click Functionality
Here's how you can integrate JavaScript buttons and click handlers:
html
User
no js just html css extend the syntatx
Assistant
Let's extend the syntax of the WebDocLang interpreter to only use HTML and CSS, while providing more styling features and structured HTML content. We'll expand the language to include more styling options and support additional HTML components like buttons that do not include JavaScript functionality.
Here’s how you can define buttons and add more styling options using only HTML and CSS:
html
User
ok now lets create an index.html that gets the index.dumb file which is our file lang thing ok?
Assistant
Certainly! Let's create a setup where you have an index.html page that reads from a custom file (e.g., index.dumb) containing your WebDocLang script. The index.html will then process this file using the interpreter we've discussed to generate and display the resulting HTML.
Here's how you can set it up:
1. Create index.html
This file will serve as the main entry point that reads and processes your custom language file (index.dumb).
html
User
just the preview no html just that no title just the preview of the webpage
Assistant
Certainly! If you want to focus solely on rendering the HTML content from a custom script file (like index.dumb) directly into a webpage without displaying any interpreter-related UI elements (such as a title, textarea, or button), you can simplify the setup. Below, I'll provide only the code necessary to display the final rendered HTML from the index.dumb file.
Simplified index.html for Rendering
Here's how you can structure index.html to read and render the content directly:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>WebLang Interpreter</title>
<style>
body { font-family: Arial, sans-serif; margin: 20px; }
textarea { width: 100%; padding: 10px; }
pre { background-color: #f4f4f4; padding: 10px; }
</style>
</head>
<body>
<h1>WebLang Interpreter</h1>
<textarea id="code" rows="10" placeholder="Write your WebLang code here...">
# Example WebLang Code
x = 10
y = 20
z = x + y
print z
</textarea>
<button onclick="run()">Run</button>
<pre id="output"></pre>
<script>
function run() {
const code = document.getElementById('code').value;
const outputElement = document.getElementById('output');
const interpreter = new WebLangInterpreter();
try {
const result = interpreter.run(code);
outputElement.textContent = result;
} catch (error) {
outputElement.textContent = 'Error: ' + error.message;
}
}
class WebLangInterpreter {
constructor() {
this.variables = {};
}
run(code) {
const lines = code.split('\n');
let output = '';
for (let line of lines) {
line = line.trim();
if (!line || line.startsWith('#')) continue; // Skip empty lines and comments
const tokens = line.split(' ');
if (tokens[0] === 'print') {
const expr = tokens.slice(1).join(' ');
const value = this.evaluate(expr);
output += value + '\n';
} else if (tokens.includes('=')) {
this.handleAssignment(tokens);
} else {
throw new Error('Unknown command: ' + line);
}
}
return output;
}
handleAssignment(tokens) {
const varName = tokens[0];
if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(varName)) {
throw new Error('Invalid variable name: ' + varName);
}
const expr = tokens.slice(2).join(' '); // Skip `varName =`
const value = this.evaluate(expr);
this.variables[varName] = value;
}
evaluate(expr) {
const sanitizedExpr = expr.replace(/[a-zA-Z_][a-zA-Z0-9_]*/g, match => {
if (this.variables.hasOwnProperty(match)) {
return this.variables[match];
} else {
throw new Error('Undefined variable: ' + match);
}
});
try {
return Function('"use strict"; return (' + sanitizedExpr + ')')();
} catch {
throw new Error('Invalid expression: ' + expr);
}
}
}
</script>
</body>
</html>
Features Explained
HTML Structure: The user writes WebLang code in a <textarea>. Clicking "Run" triggers the interpreter, and the results are shown in a <pre> element.
JavaScript (Interpreter Class):
Comments: Lines starting with # are ignored.
Variable Assignment: Uses a regular expression to validate variable names.
Expression Evaluation: Uses JavaScript's Function constructor for parsing. Variable references are replaced by their values before evaluation.
Print Command: Outputs resulted from evaluated expressions.
Using the Interpreter
Type or paste WebLang code into the textarea.
Use statements like x = 10, y = 20, z = x + y, and print z to test basic functionality.
Ensure variable names start with a letter/underscore and contain only letters, numbers, or underscores.
Observe comments and basic arithmetic.
Extensible Ideas
This code forms a base that can be expanded further:
Advanced Parsing: Introduce a proper parser with an Abstract Syntax Tree (AST).
Control Structures: Add support for loops (while, for) and conditional statements (if).
Function Definitions: Allow users to define and call functions.
This example remains simple, avoiding the complexities of error handling and advanced type support found in fully-featured languages like Python or JavaScript. For deployment in production or educational environments, further refinement and security measures would be needed.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>WebDocLang Interpreter</title>
<style>
body { font-family: Arial, sans-serif; margin: 20px; }
textarea { width: 100%; padding: 10px; }
pre { background-color: #f9f9f9; padding: 10px; white-space: pre-wrap; word-wrap: break-word; }
</style>
</head>
<body>
<h1>WebDocLang Interpreter</h1>
<textarea id="code" rows="10" placeholder="Write your WebDocLang code here...">
title My Web Page
heading Welcome to My Web Page
text This is a paragraph explaining the content of the page.
list item 1, item 2, item 3
</textarea>
<button onclick="run()">Run</button>
<pre id="output"></pre>
<div id="renderedOutput"></div>
<script>
function run() {
const code = document.getElementById('code').value;
const outputElement = document.getElementById('output');
const renderedOutput = document.getElementById('renderedOutput');
const interpreter = new WebDocLangInterpreter();
try {
const resultHtml = interpreter.run(code);
outputElement.textContent = "Generated HTML:\n" + resultHtml;
renderedOutput.innerHTML = resultHtml;
} catch (error) {
outputElement.textContent = 'Error: ' + error.message;
}
}
class WebDocLangInterpreter {
constructor() {
this.html = '';
}
run(code) {
const lines = code.split('\n');
this.html = '<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title></title></head><body>';
for (let line of lines) {
line = line.trim();
if (!line) continue; // Skip empty lines
const tokens = line.split(' ');
switch (tokens[0]) {
case 'title':
this.handleTitle(tokens.slice(1).join(' '));
break;
case 'heading':
this.handleHeading(tokens.slice(1).join(' '));
break;
case 'text':
this.handleText(tokens.slice(1).join(' '));
break;
case 'list':
this.handleList(line.slice(5).split(','));
break;
default:
throw new Error('Unknown command: ' + tokens[0]);
}
}
this.html += '</body></html>';
return this.html;
}
handleTitle(titleText) {
this.html = this.html.replace(/<title>.*<\/title>/, `<title>${titleText}</title>`);
}
handleHeading(headingText) {
this.html += `<h1>${headingText}</h1>`;
}
handleText(text) {
this.html += `<p>${text}</p>`;
}
handleList(items) {
const listItems = items.map(item => `<li>${item.trim()}</li>`).join('');
this.html += `<ul>${listItems}</ul>`;
}
}
</script>
</body>
</html>
Explanation
This code introduces a new interpreter for the language "WebDocLang":
Title: Use the title command followed by text to set the page title (displayed in the browser tab).
Heading: Use the heading command to specify an <h1> heading.
Text: The text command creates a paragraph <p>.
List: list followed by items separated by commas creates an unordered list <ul><li>.
Running the Interpreter
Input your WebDocLang code into the textarea.
Click "Run" to see both the generated HTML and its rendered result.
The interpreter displays generated HTML in a <pre> element and renders the output within a <div>.
Extending the Language
To extend WebDocLang further:
Advanced Formatting: Implement headers beyond <h1> (e.g., <h2>, <h3>) and different list types (ol, ul).
Formatting Options: Add commands for styling, such as bold, italic, and sectioning.
Links and Images: Support for <a> (links) and <img> (images).
This simple interpreter serves as a foundational learning tool for basic HTML generation through a custom scripting language. It allows beginners to understand abstract translation from a scripting language to HTML generation.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>WebDocLang Interpreter with CSS</title>
<style>
body { font-family: Arial, sans-serif; margin: 20px; }
textarea { width: 100%; padding: 10px; }
pre { background-color: #f9f9f9; padding: 10px; white-space: pre-wrap; word-wrap: break-word; }
</style>
</head>
<body>
<h1>WebDocLang Interpreter with CSS</h1>
<textarea id="code" rows="12" placeholder="Write your WebDocLang code here...">
style h1 { color: blue; text-align: center; }
style p { font-size: 14px; line-height: 1.5; }
style ul { list-style-type: square; }
title My Styled Web Page
heading Welcome to My Styled Web Page
text This is a paragraph with some basic styling applied.
list item 1, item 2, item 3
</textarea>
<button onclick="run()">Run</button>
<pre id="output"></pre>
<div id="renderedOutput"></div>
<script>
function run() {
const code = document.getElementById('code').value;
const outputElement = document.getElementById('output');
const renderedOutput = document.getElementById('renderedOutput');
const interpreter = new WebDocLangInterpreter();
try {
const resultHtml = interpreter.run(code);
outputElement.textContent = "Generated HTML:\n" + resultHtml;
renderedOutput.innerHTML = resultHtml;
} catch (error) {
outputElement.textContent = 'Error: ' + error.message;
}
}
class WebDocLangInterpreter {
constructor() {
this.html = '';
this.styles = '';
}
run(code) {
const lines = code.split('\n');
this.html = '<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title></title><style>';
for (let line of lines) {
line = line.trim();
if (!line) continue; // Skip empty lines
const tokens = line.split(' ');
switch (tokens[0]) {
case 'title':
this.handleTitle(tokens.slice(1).join(' '));
break;
case 'heading':
this.handleHeading(tokens.slice(1).join(' '));
break;
case 'text':
this.handleText(tokens.slice(1).join(' '));
break;
case 'list':
this.handleList(line.slice(5).split(','));
break;
case 'style':
this.handleStyle(line.slice(6).trim());
break;
default:
throw new Error('Unknown command: ' + tokens[0]);
}
}
this.html += this.styles + '</style></head><body>';
this.html += '</body></html>';
return this.html;
}
handleTitle(titleText) {
this.html = this.html.replace(/<title>.*<\/title>/, `<title>${titleText}</title>`);
}
handleHeading(headingText) {
this.html += `<h1>${headingText}</h1>`;
}
handleText(text) {
this.html += `<p>${text}</p>`;
}
handleList(items) {
const listItems = items.map(item => `<li>${item.trim()}</li>`).join('');
this.html += `<ul>${listItems}</ul>`;
}
handleStyle(styleText) {
this.styles += styleText + '\n';
}
}
</script>
</body>
</html>
Explanation
Style Command: You can now use the style command to define CSS styles directly in your WebDocLang script. For example:
style h1 { color: blue; text-align: center; } styles the <h1> elements to have a blue color and be centered.
style p { font-size: 14px; line-height: 1.5; } modifies paragraph text size and line spacing.
style ul { list-style-type: square; } changes the ul bullets to square.
Execution: The interpreter processes the style command, appending CSS rules into the <style> section of the generated HTML document.
Running the Updated Interpreter
Write your WebDocLang code, including style commands, within the textarea.
Click "Run" to see the generated HTML and rendered styled HTML.
Adjust styles to modify the look of each HTML element.
This version allows users learning HTML/CSS to see practical application effects by directly altering styles using a custom language interface, potentially aiding their understanding of CSS influence on document presentation.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>WebDocLang Interpreter with Enhanced Styling</title>
<style>
body { font-family: Arial, sans-serif; margin: 20px; }
textarea { width: 100%; padding: 10px; }
pre { background-color: #f9f9f9; padding: 10px; white-space: pre-wrap; word-wrap: break-word; }
</style>
</head>
<body>
<h1>WebDocLang Interpreter with Enhanced Styling</h1>
<textarea id="code" rows="12" placeholder="Write your WebDocLang code here...">
TITLE My Styled Web Page
HEADING Welcome to My Styled Web Page
TEXT This is a paragraph with some basic styling applied.
LIST item 1, item 2, item 3
STYLE TEXT p COLOR blue SIZE 14px
STYLE TEXT h1 COLOR red ALIGN center
STYLE LIST ul TYPE square
</textarea>
<button onclick="run()">Run</button>
<pre id="output"></pre>
<div id="renderedOutput"></div>
<script>
function run() {
const code = document.getElementById('code').value;
const outputElement = document.getElementById('output');
const renderedOutput = document.getElementById('renderedOutput');
const interpreter = new WebDocLangInterpreter();
try {
const resultHtml = interpreter.run(code);
outputElement.textContent = "Generated HTML:\n" + resultHtml;
renderedOutput.innerHTML = resultHtml;
} catch (error) {
outputElement.textContent = 'Error: ' + error.message;
}
}
class WebDocLangInterpreter {
constructor() {
this.html = '';
this.styles = '';
}
run(code) {
const lines = code.split('\n');
this.html = '<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title></title><style>';
for (let line of lines) {
line = line.trim();
if (!line) continue; // Skip empty lines
const tokens = line.split(' ');
switch (tokens[0].toUpperCase()) {
case 'TITLE':
this.handleTitle(tokens.slice(1).join(' '));
break;
case 'HEADING':
this.handleHeading(tokens.slice(1).join(' '));
break;
case 'TEXT':
this.handleText(tokens.slice(1).join(' '));
break;
case 'LIST':
this.handleList(line.slice(5).split(','));
break;
case 'STYLE':
this.handleStyle(tokens.slice(1));
break;
default:
throw new Error('Unknown command: ' + tokens[0]);
}
}
this.html += this.styles + '</style></head><body>';
this.html += '</body></html>';
return this.html;
}
handleTitle(titleText) {
this.html = this.html.replace(/<title>.*<\/title>/, `<title>${titleText}</title>`);
}
handleHeading(headingText) {
this.html += `<h1>${headingText}</h1>`;
}
handleText(text) {
this.html += `<p>${text}</p>`;
}
handleList(items) {
const listItems = items.map(item => `<li>${item.trim()}</li>`).join('');
this.html += `<ul>${listItems}</ul>`;
}
handleStyle(tokens) {
const element = tokens[0].toLowerCase();
let cssRules = '';
let i = 1;
while (i < tokens.length) {
switch (tokens[i].toUpperCase()) {
case 'COLOR':
cssRules += `color: ${tokens[i + 1]}; `;
i += 2;
break;
case 'SIZE':
cssRules += `font-size: ${tokens[i + 1]}; `;
i += 2;
break;
case 'ALIGN':
cssRules += `text-align: ${tokens[i + 1]}; `;
i += 2;
break;
case 'TYPE':
cssRules += `list-style-type: ${tokens[i + 1]}; `;
i += 2;
break;
default:
i++;
}
}
this.styles += `${element} { ${cssRules} }\n`;
}
}
</script>
</body>
</html>
Explanation
Enhanced STYLE Command: You can use natural language-like commands to style elements.
STYLE TEXT p COLOR blue SIZE 14px to set paragraph text to blue with a font size of 14px.
STYLE TEXT h1 COLOR red ALIGN center to set the <h1> color to red and centered.
STYLE LIST ul TYPE square for square list bullets.
These commands are parsed in a customizable, extensible way, which can accommodate more complex styles if needed. The interpreter reads these tokens and applies corresponding CSS rules, generating both style and HTML dynamically.
This allows users to see how individual styling commands affect element presentation in a straightforward, high-level scripting form. You can further refine the language commands and styling to fit additional specifications as needed.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>WebDocLang Interpreter with In-Line Styling</title>
<style>
body { font-family: Arial, sans-serif; margin: 20px; }
textarea { width: 100%; padding: 10px; }
pre { background-color: #f9f9f9; padding: 10px; white-space: pre-wrap; word-wrap: break-word; }
</style>
</head>
<body>
<h1>WebDocLang Interpreter with In-Line Styling</h1>
<textarea id="code" rows="12" placeholder="Write your WebDocLang code here...">
TITLE My Web Page
HEADING Welcome TEXT-COLOR blue TEXT-SIZE 24px
TEXT This is a paragraph explaining the content. TEXT-COLOR black TEXT-SIZE 14px
LIST item 1, item 2, item 3 COLOR red
</textarea>
<button onclick="run()">Run</button>
<pre id="output"></pre>
<div id="renderedOutput"></div>
<script>
function run() {
const code = document.getElementById('code').value;
const outputElement = document.getElementById('output');
const renderedOutput = document.getElementById('renderedOutput');
const interpreter = new WebDocLangInterpreter();
try {
const resultHtml = interpreter.run(code);
outputElement.textContent = "Generated HTML:\n" + resultHtml;
renderedOutput.innerHTML = resultHtml;
} catch (error) {
outputElement.textContent = 'Error: ' + error.message;
}
}
class WebDocLangInterpreter {
constructor() {
this.html = '';
this.styles = '';
}
run(code) {
const lines = code.split('\n');
this.html = '<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title></title><style></style></head><body>';
for (let line of lines) {
line = line.trim();
if (!line) continue; // Skip empty lines
const tokens = line.split(' ');
switch (tokens[0].toUpperCase()) {
case 'TITLE':
this.handleTitle(tokens.slice(1).join(' '));
break;
case 'HEADING':
this.handleStyledElement('h1', tokens.slice(1));
break;
case 'TEXT':
this.handleStyledElement('p', tokens.slice(1));
break;
case 'LIST':
this.handleStyledList(tokens.slice(1));
break;
default:
throw new Error('Unknown command: ' + tokens[0]);
}
}
this.html += '</body></html>';
return this.html;
}
handleTitle(titleText) {
this.html = this.html.replace(/<title>.*<\/title>/, `<title>${titleText}</title>`);
}
handleStyledElement(element, tokens) {
let content = '';
let style = '';
tokens.forEach((token, i) => {
switch (token.toUpperCase()) {
case 'TEXT-COLOR':
style += `color: ${tokens[i + 1]}; `;
break;
case 'TEXT-SIZE':
style += `font-size: ${tokens[i + 1]}; `;
break;
default:
if (!tokens[i - 1] || (tokens[i - 1].toUpperCase() !== 'TEXT-COLOR' && tokens[i - 1].toUpperCase() !== 'TEXT-SIZE')) {
content += token + ' ';
}
break;
}
});
this.html += `<${element} style="${style.trim()}">${content.trim()}</${element}>`;
}
handleStyledList(tokens) {
let items = tokens.join(' ').split(',');
let listItems = '';
let style = '';
// Check for inline style command for LIST
items = items.map(item => item.trim());
if (tokens.includes('COLOR')) {
const colorIndex = tokens.indexOf('COLOR');
style += `color: ${tokens[colorIndex + 1]}; `;
items = items.filter(item => !item.startsWith(`COLOR ${tokens[colorIndex + 1]}`));
}
items.forEach(item => {
listItems += `<li>${item}</li>`;
});
this.html += `<ul style="${style.trim()}">${listItems}</ul>`;
}
}
</script>
</body>
</html>
Explanation
In-line Styling: Each element (heading, text, list) can have styles specified:
HEADING Welcome TEXT-COLOR blue TEXT-SIZE 24px: Sets text color to blue and size to 24px for the heading.
TEXT ... TEXT-COLOR black TEXT-SIZE 14px: Changes the paragraph's text color and size.
LIST item 1, item 2, item 3 COLOR red: Specifies list text color directly.
Parsing: In the JavaScript interpreter, the handleStyledElement and handleStyledList functions parse content and styling instructions, creating HTML elements with embedded styles.
Output: Writing these in-line allows users to specify styles succinctly within their document structure, following a simple and consistent format.
This revised setup demonstrates how users can directly impact the styling of their generated HTML content while still using a straightforward scripting syntax. Further expansions could include additional style attributes (like background colors or borders) to broaden styling capabilities.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>WebDocLang Interpreter</title>
<style>
body { font-family: Arial, sans-serif; margin: 20px; }
textarea { width: 100%; padding: 10px; }
pre { background-color: #f9f9f9; padding: 10px; white-space: pre-wrap; word-wrap: break-word; }
</style>
</head>
<body>
<h1>WebDocLang Interpreter</h1>
<textarea id="code" rows="12" placeholder="Write your WebDocLang code here...">
TITLE My Web Page
HEADING Welcome COLOR blue SIZE 24px
TEXT This is a paragraph explaining the content. COLOR black SIZE 14px
LIST item1, item2, item3 COLOR red
</textarea>
<button onclick="run()">Run</button>
<pre id="output"></pre>
<div id="renderedOutput"></div>
<script>
function run() {
const code = document.getElementById('code').value;
const outputElement = document.getElementById('output');
const renderedOutput = document.getElementById('renderedOutput');
const interpreter = new WebDocLangInterpreter();
try {
const resultHtml = interpreter.run(code);
outputElement.textContent = "Generated HTML:\n" + resultHtml;
renderedOutput.innerHTML = resultHtml;
} catch (error) {
outputElement.textContent = 'Error: ' + error.message;
}
}
class WebDocLangInterpreter {
constructor() {
this.html = '';
}
run(code) {
const lines = code.split('\n');
this.html = '<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title></title><style></style></head><body>';
for (let line of lines) {
line = line.trim();
if (!line) continue; // Skip empty lines
const tokens = line.split(' ');
switch (tokens[0].toUpperCase()) {
case 'TITLE':
this.handleTitle(tokens.slice(1).join(' '));
break;
case 'HEADING':
this.handleElement('h1', tokens.slice(1));
break;
case 'TEXT':
this.handleElement('p', tokens.slice(1));
break;
case 'LIST':
this.handleList(tokens.slice(1));
break;
default:
throw new Error('Unknown command: ' + tokens[0]);
}
}
this.html += '</body></html>';
return this.html;
}
handleTitle(titleText) {
this.html = this.html.replace(/<title>.*<\/title>/, `<title>${titleText}</title>`);
}
handleElement(tag, tokens) {
let content = '';
let style = '';
tokens.forEach((token, i) => {
switch (token.toUpperCase()) {
case 'COLOR':
style += `color: ${tokens[i + 1]}; `;
break;
case 'SIZE':
style += `font-size: ${tokens[i + 1]}; `;
break;
default:
if (!tokens[i - 1] || (tokens[i - 1].toUpperCase() !== 'COLOR' && tokens[i - 1].toUpperCase() !== 'SIZE')) {
content += token + ' ';
}
break;
}
});
this.html += `<${tag} style="${style.trim()}">${content.trim()}</${tag}>`;
}
handleList(tokens) {
let items = tokens.join(' ').split(',');
let style = '';
items = items.map(item => item.trim());
if (tokens.includes('COLOR')) {
const colorIndex = tokens.indexOf('COLOR');
style += `color: ${tokens[colorIndex + 1]}; `;
items = items.filter((item, index) => index < colorIndex || index >= colorIndex + 2);
}
const listItems = items.map(item => `<li>${item}</li>`).join('');
this.html += `<ul style="${style.trim()}">${listItems}</ul>`;
}
}
</script>
</body>
</html>
Key Features
Natural Language-Like Syntax:
HEADING Welcome COLOR blue SIZE 24px: This command sets the heading's color to blue and size to 24px.
TEXT ... COLOR black SIZE 14px: This sets the paragraph text to black and the size to 14px.
LIST item1, item2, item3 COLOR red: This command creates a list with red text.
Inline Style Handling: Each command parses inline styles directly alongside the HTML content parameters, allowing for intuitive reading and writing of script.
Flexible Parsing: The interpreter flexibly expands to include additional attributes or different HTML tags by plugging more cases into the switch statements and writing respective handlers.
This setup is great for teaching or experimenting with basic styles and HTML structures while staying within a simple, constrained scripting environment!
Feel free to expand or customize further based on your exact needs or new features you might want to add (such as backgrounds, borders, etc.).
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>WebDocLang Interpreter with Button Clicks</title>
<style>
body { font-family: Arial, sans-serif; margin: 20px; }
textarea { width: 100%; padding: 10px; }
pre { background-color: #f9f9f9; padding: 10px; white-space: pre-wrap; word-wrap: break-word; }
</style>
</head>
<body>
<h1>WebDocLang Interpreter with Button Clicks</h1>
<textarea id="code" rows="12" placeholder="Write your WebDocLang code here...">
TITLE My Web Page
HEADING Click the button below COLOR blue SIZE 24px
BUTTON Click Me ACTION alert('Button Clicked!')
TEXT Below is a demonstration of button interaction. COLOR black SIZE 14px
</textarea>
<button onclick="run()">Run</button>
<pre id="output"></pre>
<div id="renderedOutput"></div>
<script>
function run() {
const code = document.getElementById('code').value;
const outputElement = document.getElementById('output');
const renderedOutput = document.getElementById('renderedOutput');
const interpreter = new WebDocLangInterpreter();
try {
const resultHtml = interpreter.run(code);
outputElement.textContent = "Generated HTML:\n" + resultHtml;
renderedOutput.innerHTML = resultHtml;
} catch (error) {
outputElement.textContent = 'Error: ' + error.message;
}
}
class WebDocLangInterpreter {
constructor() {
this.html = '';
}
run(code) {
const lines = code.split('\n');
this.html = '<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title></title><style></style><script></script></head><body>';
for (let line of lines) {
line = line.trim();
if (!line) continue; // Skip empty lines
const tokens = line.split(' ');
switch (tokens[0].toUpperCase()) {
case 'TITLE':
this.handleTitle(tokens.slice(1).join(' '));
break;
case 'HEADING':
this.handleElement('h1', tokens.slice(1));
break;
case 'TEXT':
this.handleElement('p', tokens.slice(1));
break;
case 'BUTTON':
this.handleButton(tokens.slice(1));
break;
default:
throw new Error('Unknown command: ' + tokens[0]);
}
}
this.html += '</body></html>';
return this.html;
}
handleTitle(titleText) {
this.html = this.html.replace(/<title>.*<\/title>/, `<title>${titleText}</title>`);
}
handleElement(tag, tokens) {
let content = '';
let style = '';
tokens.forEach((token, i) => {
switch (token.toUpperCase()) {
case 'COLOR':
style += `color: ${tokens[i + 1]}; `;
break;
case 'SIZE':
style += `font-size: ${tokens[i + 1]}; `;
break;
default:
if (!tokens[i - 1] || (tokens[i - 1].toUpperCase() !== 'COLOR' && tokens[i - 1].toUpperCase() !== 'SIZE')) {
content += token + ' ';
}
break;
}
});
this.html += `<${tag} style="${style.trim()}">${content.trim()}</${tag}>`;
}
handleButton(tokens) {
let label = '';
let action = '';
tokens.forEach((token, i) => {
if (token.toUpperCase() === 'ACTION') {
action = tokens.slice(i + 1).join(' ');
return;
}
if (!action) {
label += token + ' ';
}
});
// Add a unique ID to the button to hook the JS function
const buttonId = `button-${Math.random().toString(36).substr(2, 9)}`;
this.html += `<button id="${buttonId}">${label.trim()}</button>`;
this.html = this.html.replace(/<script><\/script>/, `<script>document.getElementById('${buttonId}').onclick = function() { ${action} };</script>`);
}
}
</script>
</body>
</html>
Explanation
Button Definition:
BUTTON Click Me ACTION alert('Button Clicked!'): Defines a button with the label "Click Me" and an action that shows an alert when clicked.
JavaScript Integration:
The handleButton method parses the BUTTON command and attaches a click event using a unique ID for the button.
The click action specifies a JavaScript code snippet to execute upon the button being clicked (e.g., alert('Button Clicked!')).
Flexible Command Parsing:
The interpreter allows embedding JavaScript functions within the ACTION keyword, enabling customized interactivity.
It assigns unique IDs to buttons for resolving script-scope issues in dynamically generated content.
Usage
Define Buttons: Use the BUTTON command to define interactive elements.
Specify Actions: Embed JavaScript logic within the ACTION keyword to dictate interactive behavior.
With this addition, you can handle user interactions directly from your WebDocLang scripts, simulating basic web application behavior and enhancing interactivity in your generated HTML documents. This setup offers a great starting point for embedding interactive elements in your custom language.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>WebDocLang Interpreter</title>
<style>
body { font-family: Arial, sans-serif; margin: 20px; }
textarea { width: 100%; padding: 10px; }
pre { background-color: #f9f9f9; padding: 10px; white-space: pre-wrap; word-wrap: break-word; }
</style>
</head>
<body>
<h1>WebDocLang Interpreter</h1>
<textarea id="code" rows="15" placeholder="Write your WebDocLang code here...">
TITLE My Web Page
HEADING Welcome to My Page COLOR blue SIZE 24px
TEXT This is a paragraph about my page. FONT-STYLE italic SIZE 16px
TEXT Another paragraph with different styling. COLOR green SIZE 14px
LIST First item, Second item, Third item COLOR red
BUTTON Press Me BG-COLOR lightgrey SIZE 18px WEIGHT bold
</textarea>
<button onclick="run()">Run</button>
<pre id="output"></pre>
<div id="renderedOutput"></div>
<script>
function run() {
const code = document.getElementById('code').value;
const outputElement = document.getElementById('output');
const renderedOutput = document.getElementById('renderedOutput');
const interpreter = new WebDocLangInterpreter();
try {
const resultHtml = interpreter.run(code);
outputElement.textContent = "Generated HTML:\n" + resultHtml;
renderedOutput.innerHTML = resultHtml;
} catch (error) {
outputElement.textContent = 'Error: ' + error.message;
}
}
class WebDocLangInterpreter {
constructor() {
this.html = '';
}
run(code) {
const lines = code.split('\n');
this.html = '<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title></title></head><body>';
for (let line of lines) {
line = line.trim();
if (!line) continue; // Skip empty lines
const tokens = line.split(' ');
switch (tokens[0].toUpperCase()) {
case 'TITLE':
this.handleTitle(tokens.slice(1).join(' '));
break;
case 'HEADING':
this.handleElement('h1', tokens.slice(1));
break;
case 'TEXT':
this.handleElement('p', tokens.slice(1));
break;
case 'LIST':
this.handleList(tokens.slice(1));
break;
case 'BUTTON':
this.handleElement('button', tokens.slice(1));
break;
default:
throw new Error('Unknown command: ' + tokens[0]);
}
}
this.html += '</body></html>';
return this.html;
}
handleTitle(titleText) {
this.html = this.html.replace(/<title>.*<\/title>/, `<title>${titleText}</title>`);
}
handleElement(tag, tokens) {
let content = '';
let style = '';
tokens.forEach((token, i) => {
switch (token.toUpperCase()) {
case 'COLOR':
style += `color: ${tokens[i + 1]}; `;
break;
case 'SIZE':
style += `font-size: ${tokens[i + 1]}; `;
break;
case 'FONT-STYLE':
style += `font-style: ${tokens[i + 1]}; `;
break;
case 'WEIGHT':
style += `font-weight: ${tokens[i + 1]}; `;
break;
case 'BG-COLOR':
style += `background-color: ${tokens[i + 1]}; `;
break;
default:
if (!tokens[i - 1] || !['COLOR', 'SIZE', 'FONT-STYLE', 'WEIGHT', 'BG-COLOR'].includes(tokens[i - 1].toUpperCase())) {
content += token + ' ';
}
break;
}
});
this.html += `<${tag} style="${style.trim()}">${content.trim()}</${tag}>`;
}
handleList(tokens) {
let items = tokens.join(' ').split(',');
let style = '';
items = items.map(item => item.trim());
if (tokens.includes('COLOR')) {
const colorIndex = tokens.indexOf('COLOR');
style += `color: ${tokens[colorIndex + 1]}; `;
items = items.filter((item, index) => index < colorIndex || index >= colorIndex + 2);
}
const listItems = items.map(item => `<li>${item}</li>`).join('');
this.html += `<ul style="${style.trim()}">${listItems}</ul>`;
}
}
</script>
</body>
</html>
Explanation
Extended Styling Commands:
COLOR: Sets the text color.
SIZE: Sets the font size.
FONT-STYLE: Sets font style such as italic.
WEIGHT: Sets font weight, e.g., bold.
BG-COLOR: Specifies the background color of the button.
Additional HTML Components:
Buttons as HTML elements without functionality, styled with a background color, size, and weight as outlined.
How It Works:
The interpreter processes each line, identifying the type of HTML element (e.g., HEADING, TEXT, BUTTON) and applies inline styles.
Specifies textual content and styling attributes all within the command line.
This version allows users to create a more enhanced structured document using broader styling commands while maintaining a simple interface for adding content to HTML. The approach is useful for teaching or quickly prototyping designs in a simplified manner.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>WebDocLang Interpreter</title>
<style>
body { font-family: Arial, sans-serif; margin: 20px; }
pre { background-color: #f9f9f9; padding: 10px; white-space: pre-wrap; word-wrap: break-word; }
</style>
</head>
<body>
<h1>WebDocLang Interpreter</h1>
<pre id="output"></pre>
<div id="renderedOutput"></div>
<script>
// Function to fetch and read the index.dumb file
async function loadScript() {
try {
const response = await fetch('index.dumb');
const code = await response.text();
interpret(code);
} catch (error) {
document.getElementById('output').textContent = 'Error: ' + error.message;
}
}
// Interpreter function
function interpret(code) {
const outputElement = document.getElementById('output');
const renderedOutput = document.getElementById('renderedOutput');
const interpreter = new WebDocLangInterpreter();
try {
const resultHtml = interpreter.run(code);
outputElement.textContent = "Generated HTML:\n" + resultHtml;
renderedOutput.innerHTML = resultHtml;
} catch (error) {
outputElement.textContent = 'Error: ' + error.message;
}
}
// Run the interpreter as soon as the page loads
window.onload = loadScript;
// Define the WebDocLangInterpreter class
class WebDocLangInterpreter {
constructor() {
this.html = '';
}
run(code) {
const lines = code.split('\n');
this.html = '<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title></title></head><body>';
for (let line of lines) {
line = line.trim();
if (!line) continue; // Skip empty lines
const tokens = line.split(' ');
switch (tokens[0].toUpperCase()) {
case 'TITLE':
this.handleTitle(tokens.slice(1).join(' '));
break;
case 'HEADING':
this.handleElement('h1', tokens.slice(1));
break;
case 'TEXT':
this.handleElement('p', tokens.slice(1));
break;
case 'LIST':
this.handleList(tokens.slice(1));
break;
case 'BUTTON':
this.handleElement('button', tokens.slice(1));
break;
default:
throw new Error('Unknown command: ' + tokens[0]);
}
}
this.html += '</body></html>';
return this.html;
}
handleTitle(titleText) {
this.html = this.html.replace(/<title>.*<\/title>/, `<title>${titleText}</title>`);
}
handleElement(tag, tokens) {
let content = '';
let style = '';
tokens.forEach((token, i) => {
switch (token.toUpperCase()) {
case 'COLOR':
style += `color: ${tokens[i + 1]}; `;
break;
case 'SIZE':
style += `font-size: ${tokens[i + 1]}; `;
break;
case 'FONT-STYLE':
style += `font-style: ${tokens[i + 1]}; `;
break;
case 'WEIGHT':
style += `font-weight: ${tokens[i + 1]}; `;
break;
case 'BG-COLOR':
style += `background-color: ${tokens[i + 1]}; `;
break;
default:
if (!tokens[i - 1] || !['COLOR', 'SIZE', 'FONT-STYLE', 'WEIGHT', 'BG-COLOR'].includes(tokens[i - 1].toUpperCase())) {
content += token + ' ';
}
break;
}
});
this.html += `<${tag} style="${style.trim()}">${content.trim()}</${tag}>`;
}
handleList(tokens) {
let items = tokens.join(' ').split(',');
let style = '';
items = items.map(item => item.trim());
if (tokens.includes('COLOR')) {
const colorIndex = tokens.indexOf('COLOR');
style += `color: ${tokens[colorIndex + 1]}; `;
items = items.filter((item, index) => index < colorIndex || index >= colorIndex + 2);
}
const listItems = items.map(item => `<li>${item}</li>`).join('');
this.html += `<ul style="${style.trim()}">${listItems}</ul>`;
}
}
</script>
</body>
</html>
2. Create index.dumb
The index.dumb file will contain your custom WebDocLang script. Here’s an example:
code
TITLE My Web Page
HEADING Welcome to My Page COLOR blue SIZE 24px
TEXT This is a paragraph about my page. FONT-STYLE italic SIZE 16px
TEXT Another paragraph with different styling. COLOR green SIZE 14px
LIST First item, Second item, Third item COLOR red
BUTTON Press Me BG-COLOR lightgrey SIZE 18px WEIGHT bold
How It Works
File Reading: The loadScript function within index.html fetches the content of index.dumb using fetch and reads it as text when the page loads.
Language Processing: The content from index.dumb is parsed and interpreted by the WebDocLangInterpreter class, generating and displaying the HTML structure in renderedOutput.
Enhancements: You can further extend this setup to watch for file changes or have more interactive UI elements, but this is a robust foundational setup for reading and processing custom script files.
This approach demonstrates how to integrate custom scripting logic with traditional web development practices seamlessly, leveraging the web's native capabilities to interpret and render content dynamically.
Rendering Only: The script directly interprets the content of index.dumb and renders it inside the #renderedOutput div without any additional UI components.
Automatic Execution: The window.onload ensures the script file is loaded and interpreted as soon as the page loads.
Error Handling: Console logging for any errors encountered while loading or interpreting the script.
index.dumb File (as before)
code
HEADING Welcome to My Page COLOR blue SIZE 24px
TEXT This is a paragraph about my page. FONT-STYLE italic SIZE 16px
TEXT Another paragraph with different styling. COLOR green SIZE 14px
LIST First item, Second item, Third item COLOR red
BUTTON Press Me BG-COLOR lightgrey SIZE 18px WEIGHT bold
This setup effectively creates a minimal environment where the interpreted content from your custom script is directly rendered on the page, focusing solely on the content display. It leverages the strengths of HTML and CSS while interpreting custom language constructs.