Skip to content

Instantly share code, notes, and snippets.

@lantos1618
Created April 1, 2024 13:53
Show Gist options
  • Save lantos1618/f72e243f3cbdd33fe0c8363e8d9770cf to your computer and use it in GitHub Desktop.
Save lantos1618/f72e243f3cbdd33fe0c8363e8d9770cf to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
typedef enum {
TAG_HTML,
TAG_HEAD,
TAG_BODY,
TAG_TITLE,
TAG_H1,
TAG_H2,
TAG_H3,
TAG_P,
TAG_A,
} HtmlTag;
typedef struct HtmlNode {
HtmlTag tag;
char* content;
struct HtmlNode* children;
} HtmlNode;
char* tagToString(HtmlTag tag) {
switch (tag) {
case TAG_HTML:
return "html";
case TAG_HEAD:
return "head";
case TAG_BODY:
return "body";
case TAG_TITLE:
return "title";
case TAG_H1:
return "h1";
case TAG_H2:
return "h2";
case TAG_H3:
return "h3";
case TAG_P:
return "p";
case TAG_A:
return "a";
default:
return "unknown";
}
}
void printNode(HtmlNode* node) {
char* tagStr = tagToString(node->tag);
printf("<%s>", tagStr);
if (node->content) {
printf("%s", node->content);
}
HtmlNode* child = node->children;
while (child) {
printNode(child);
child = child->children;
}
printf("</%s>", tagStr);
}
HtmlNode* addChild(HtmlNode* parent, HtmlNode* child) {
if (!parent->children) {
parent->children = child;
} else {
HtmlNode* current = parent->children;
while (current->children) {
current = current->children;
}
current->children = child;
}
return parent;
}
HtmlNode* createNode(HtmlTag tag, char* content, ...) {
HtmlNode* node = (HtmlNode*)malloc(sizeof(HtmlNode));
node->tag = tag;
node->content = content;
node->children = NULL;
va_list args;
va_start(args, content);
HtmlNode* child = va_arg(args, HtmlNode*);
while (child) {
node = addChild(node, child);
child = va_arg(args, HtmlNode*);
}
va_end(args);
return node;
}
#define html(...) createNode(TAG_HTML, NULL, __VA_ARGS__, NULL)
#define head(...) createNode(TAG_HEAD, NULL, __VA_ARGS__, NULL)
#define body(...) createNode(TAG_BODY, NULL, __VA_ARGS__, NULL)
#define title(text) createNode(TAG_TITLE, text, NULL)
#define h1(text) createNode(TAG_H1, text, NULL)
int main() {
HtmlNode* node = html(
head(
title("sadfasd")
),
body(
h1("hello")
)
);
printNode(node);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment